How to get Class properties in java?

We often need to have a Class object and its properties, lets see how we can get them or use them. We will see how we will get the Class object, name of the Class object, getting package name of the Class, getting the interfaces implemented by a Class.

1. Getting the Class object :

There are three ways to retrieve the Class object.

1. Using .class

 
classObj = java.lang.String.class;


2. Using an Object , we can get the Class object using getClass() method.
 
Class classObj = object.getClass();


3. Using String
We can use Class.forName to get the Class object.
 
try{
classObj = Class.forName( "java.lang.String" );
}catch( ClassNotFoundException es ){

}


2. Getting the name of Class object

1. Getting fully qualified domain name of Class or InnerClass
 
String className = classObj.getName();

2. Getting the name of primitive type :

 
String className = int.class.getName();


3. Getting the package name of a Class

We can get Package object using the classObj.getPackage() and we can have getName() to get the package name.

  
Class classObj = java.lang.String.class;
Package pkj = classObj.getPackage();
String packageName = pkj.getName();


4. Getting Super class of a Class object

For getting SuperClass of a class object we can use the method getSuperClass(). This method returns null for Object class, Interface and primitive types.

 
Class superClassObj = classObj.getSuperClass();



5. Getting the interfaces which Class implements

For getting the interfaces which Class implements there is a method getInterfaces(), for primitive type it simply returns an empty array.

 
Class[] infObj = classObj.getInterfaces();


6. How to determine a class represents a Class or an Interface

We can use isInterface() method to get the type whether it is a Class or an Interface.

  
Class classObj = java.lang.String.class;
boolean isInterface = classObj.isInterface(); // false

Class classObj = java.util.Enumeration.class;
boolean isInterface = classObj.isInterface(); // true


7. How to get a location from where Class has been loaded

For this purpose, we can use the Classes like ProtectionDomain and CodeSource, ProtectionDomain has information about CodeSource . Codesource gives the location using getLocation method.

 
Class classObj = Class.getClass();
ProtectionDomain protDomain = classObj.getProtectionDomain();
CodeSource codeSource = protDomain.getCodeSource();
URL classLoc = codeSource.getLocation();
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment