Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to get java class information using reflection

In this article we will describe one on the main feature of java, which is known as reflection.

Introduction:

The power of reflection is widely used in real time java applications. Reflection mechanism is used to find the information about java classes.

Reflection in java can be described as a mechanism to get information about java classes. As the name suggests, the mechanism reflects the information of java classes like name, super class etc. But we need to understand that the class must be loaded first to get its information. This feature is available in java version 1.1 and later. So to make it simple, a java application can discover the information about other loaded java classes by using reflection API.

In java, the reflection API is applicable on public members of an object. Due to security restriction the some access limitations are to be maintained by the java virtual machine. This is also applicable to all the members defined by a class. The most important methods like constructors, number of parameters and its types etc are available in java 1.1 and later. The completely matured reflection mechanism is available in later version of java APIs.

Java reflection class hierarchy

Figure 1: Java reflection class hierarchy

Getting class hierarchy:

We will start with the simple level of reflection implementation. The java class 'Class' is used to inspect class information in java application. The class 'Class' is located in the package java.lang. There are several methods available in class 'Class' but some of them are more important than the others. We will first investigate the simple methods like getName () and getSuperClass (). The first method is used to get the name of the loaded class and the second method returns the name of the super class or parent class. And the reflection mechanism is used in retrieving the details.

Let us take an example to clarify the basic reflection concepts. The main class is loading a class by using Class.forName () method and passed it to a second method to get details information about it. The entire reflection mechanism has been encapsulated inside the second method printDetails ().In the second method, the class name and its super classes have been retrieved by using reflection API. Please note that the reflection class 'Class' and its methods are a part of the java.lang package. So we do not need to import it separately. This is the simplest form of reflection implementation.

Listing 1: The sample displays the implemented class name and super class using reflection

/**
* Checking the basic reflection
* Author: Kaushik Pal
* */	
public class Test {
	/**
	 * @param args
	 */
	public static void main(String[] args) {		
			
		// Creating the constructor
		Test inspectclass = new Test();	      

	    try {
	           // Call printDetails class to check the details	
inspectclass.printDetails( Class.forName( "java.io.BufferedWriter" ), 0 );	        	  
	      } catch (ClassNotFoundException e ) 
	      {	    	  
		       System.out.println("Printing exception");
		       e.printStackTrace();
	      } 		
	}
	/**
	 * @param clstype
	 * @param classdepth
	 * This is used to encapsulate the reflection class details
	 */
	public void printDetails(Class clstype, int classdepth ){				
		 // Print the class name passed from main
System.out.println( "Class depth is: " + classdepth + " Class Name is: " + clstype.getName() );
	      
	      // Recurse to get super class details
	      if ( clstype.getSuperclass() != null ){
	    	  // Get all the details
	    	  printDetails( clstype.getSuperclass(), classdepth + 1 );
	      }
	}
}

The output of the application after compilation would be as shown below. It shows the class hierarchy up to Object class. The depth is also displayed as 0,1 and 2.

Class depth is: 0 Class Name is: java.io.BufferedWriter
Class depth is: 1 Class Name is: java.io.Writer
Class depth is: 2 Class Name is: java.lang.Object

If you check the output carefully then you can see that the input class is followed by the parent classes. The end class is the mother of all classes java.lang.object. The output classes are displayed with full qualified path name as the class names are stored within a particular scope.

Getting interface hierarchy:

Now we will check the implemented interfaces used by the input class.

This feature is implemented in Java 1.02 or later. It is used to list the implemented interfaces and extended classes by using reflection API. The getInterface () method is used in a loop to get the interface details of the input class.

Listing 2: The sample displays the implemented interfaces using reflection

/**
* Checking interfaces using reflection API
* Author: Kaushik Pal
* */
public class RefBasicTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// Creating the constructor
			RefBasicTest inspectclass = new RefBasicTest();	      

		    try{
		         // Call printDetails class to check the details	
inspectclass.printDetails( Class.forName( "java.io.BufferedWriter" ), 0 );	        	  
		      } catch (ClassNotFoundException e ) 
		      {	    	  
			       System.out.println("Printing exception");
			       e.printStackTrace();
		      } 		
		}
	/**
	 * @param clstype
	 * @param classdepth
	 * This is used to encapsulate the reflection class details
	 */
	public void printDetails(Class clstype, int classdepth ){				
		// Print the class name passed from main
System.out.println( "Class depth is: " + classdepth + " Class Name is: " + clstype.getName() );
		      
		// Recurse to get super class details
		if ( clstype.getSuperclass() != null ){
		  	  // Get all the details
		   	  printDetails( clstype.getSuperclass(), classdepth + 1 );
		  }
		
	    // Get all the interfaces that the input class implements.
	    Class[] interfacesimp = clstype.getInterfaces();
	    
	    System.out.println("Printing the implemented interfaces");
	    for (int i = 0; i < interfacesimp.length; i++ ) {

	    	printDetails( interfacesimp[ i ], classdepth + 1 );
	    }
	 }
}

Handling security issues in java reflection:

Security is an important aspect when we use reflection in java applications. As we know applets are signed by trusted authorities to grant security privileges but at the same time the security concern is not there for applications. Similarly as we are accessing class details some security mechanism has to be followed to make the application more secure. Let us discuss the security approaches followed in reflection.

  • Step 1: We have already discussed that the class 'Class' is the main source to access other class details, methods, interfaces etc. So to implement security, the checking starts from this point only. The class 'Class' passes the security responsibility to the system security manager. The security manager has a method called checkMemberAccess (Class, int) and it checks the permission for each class. During checking permission, exception is thrown if permission is denied.
  • Step 2: After passing the security check in step 1, the application can query and information regarding the reflected member. So the security check in the first phase is the most important one. Now if we want to operate of the underlying members of objects then java standard language checking comes into picture. So the access is allowed up to a certain level and after that no one can acces and modifies things. If we think deeply then we can understand that access to all level will only make the language in secured. So the restrictions are imposed keeping all these points in mind.

What can not be done using reflection?

After discussing the security issues we can consider the following points which can not be done using reflection

  • Using the 'Constructor' class to create and initialize new instance is not allowed
  • Using the 'Method' class to invoke methods are not allowed
  • Using the 'Field' class to set and get field values are not allowed

Conclusion

Java reflection is an important concept to understand java programming model. The reflection mechanism has been made more flexible and useful in later versions of java. In this article we have discussed the entire working flow of java reflection API. So we can use the API effectively to inspect java classes and its details during run time. The run time determination of classes and its properties are very important from application perspective. So the power and flexibility of reflection API helps java developers to make more meaningful and extensible application.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login