Basics of Java Reflection Class - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Basics of Java Reflection Class

Share This

We are taking this example as we are assuming that you have a basic understanding of Java Database Connectivity (JDBC), if not, please read it here. In JDBC we have used a class Class, which is being loaded at runtime. Here, you will understand how reflection helps us to do many things.

By inspecting a class, you can get information, such as Class Name, Class Modifies, Package Info, Superclass, Implemented Interfaces, Constructors, Methods, Fields, Annotations, etc.

In this example, we are loading the Driver class from MySQL connector jar by using Class class = Class.forName("com.mysql.jdbc.Driver");. If you receive an object in your program, you can hold the object using a reference of class Class.

If the class is not available at runtime, an exception ClassNotFoundException is thrown. After obtaining this reference, you can inspect the class. A sample code is shown below.
Content of TestMain.java
package com.t4b.test; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; public class TestMain { static Class<?> c; public static void main(String[] args) { try { c = Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println(c.getName()); System.out.println(c.getCanonicalName()); System.out.println(c.getModifiers()); System.out.println(c.getSimpleName()); System.out.println(c.isLocalClass()); System.out.println(c.isMemberClass()); System.out.println(c.isSynthetic()); System.out.println(c.getSuperclass()); System.out.println(c.getSuperclass().getSuperclass()); } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.