Java Reflection Example - BunksAllowed

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

Community

Java Reflection Example

Share This


Java Reflection (part of the java.lang.reflect package and java.lang.Class package) provides the ability to inspect and modify the run-time behavior of applications. It is a very powerful and useful technique.

Using this technique, a class or an interface can be inspected. The fields, constructors, and methods can be retrieved at run-time.

Moreover, it can be used to load a class dynamically, instantiate the class, invoke its methods, and change the values of fields.

Let us start with an example, as follow. In this example, we are trying to load the MySQL Driver class at run-time. The driver class is available in the MySQL connector jar.

In this tutorial, sample codes are developed using Eclipse IDE. Hence, you can download the codes, import them into Eclipse IDE and test them.

You may try the following code.


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()); System.out.println("Methods:"); for (Method m : c.getMethods()) { System.out.println("Method: " + m); System.out.println(" Return Type: " + m.getReturnType()); for (Type t : m.getParameterTypes()) System.out.println(" Arguments: " + t.toString()); } System.out.println("Constructors:"); for (Constructor<?> cons : c.getConstructors()) { System.out.println("Constructor: " + cons); for (Type t : cons.getParameterTypes()) System.out.println(" Arguments: " + t.toString()); } System.out.println("Fields:"); for (Field field : c.getDeclaredFields()) { System.out.println(field.getName()); System.out.println(field.getType()); } System.out.println("Interfaces:"); for (Class<?> cls : c.getInterfaces()) { System.out.println(cls.getName()); } } }
Content of Main.java
package com.t4b.test; import static java.lang.System.out; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String... args) { try { Class<?> cls = Class.forName("sun.net.spi.nameservice.dns.DNSNameService"); System.out.println(cls.getClass().isInterface()); String s1 = new String("Hello..."); System.out.println(s1); String s2 = null; try { s2 = s1.getClass().newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } System.out.println(s1 + s2); out.format("Class:%n %s%n%n", cls.getCanonicalName()); out.format("Modifiers:%n %s%n%n", Modifier.toString(cls.getModifiers())); out.format("Type Parameters:%n"); TypeVariable[] tv = cls.getTypeParameters(); if (tv.length != 0) { out.format(" "); for (TypeVariable t : tv) out.format("%s ", t.getName()); out.format("%n%n"); } else { out.format(" -- No Type Parameters --%n%n"); } out.format("Implemented Interfaces:%n"); Type[] intfs = cls.getGenericInterfaces(); if (intfs.length != 0) { for (Type intf : intfs) out.format(" %s%n", intf.toString()); out.format("%n"); } else { out.format(" -- No Implemented Interfaces --%n%n"); } out.format("Inheritance Path:%n"); List<Class> l = new ArrayList<Class>(); printAncestor(cls, l); if (l.size() != 0) { for (Class<?> cl : l) out.format(" %s%n", cl.getCanonicalName()); out.format("%n"); } else { out.format(" -- No Super Classes --%n%n"); } out.format("Annotations:%n"); Annotation[] ann = cls.getAnnotations(); if (ann.length != 0) { for (Annotation a : ann) out.format(" %s%n", a.toString()); out.format("%n"); } else { out.format(" -- No Annotations --%n%n"); } // production code should handle this exception more gracefully } catch (ClassNotFoundException x) { x.printStackTrace(); } } private static void printAncestor(Class<?> c, List<Class> l) { Class<?> ancestor = c.getSuperclass(); if (ancestor != null) { l.add(ancestor); printAncestor(ancestor, l); } } }

Happy Exploring!

No comments:

Post a Comment

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