Monday, 25 April 2016

How to inspect classes using Reflection ?


Reflection API
Using Reflection API's it is possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time.
It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.


Inspecting classes
Get Class type object
If you know the name of the class at compile time you can obtain a Class object like this :
Class aClass = MyClass.class

If you don't know the name at compile time, but have the class name as a string at runtime :
Class aClass = Class.forName(className);

Get class name
String className = aClass.getName()
String simpleClassName = aClass.getSimpleName();

Get class modifiers
int modifiers = aClass.getModifiers();

You can check the modifiers using these methods in the class java.lang.reflect.Modifiers :
Modifiers.isAbstract(int modifiers)
Modifiers.isFinal(int modifiers)
Modifiers.isInterface(int modifiers)
Modifiers.isNative(int modifiers)
Modifiers.isPrivate(int modifiers)
Modifiers.isProtected(int modifiers)
Modifiers.isPublic(int modifiers)
Modifiers.isStatic(int modifiers)
Modifiers.isStrict(int modifiers)
Modifiers.isSynchronized(int modifiers)
Modifiers.isTransient(int modifiers)
Modifiers.isVolatile(int modifiers)

Get package, super class, interfaces implemented, constructors, methods, fields, annotations of a class
Package package = aClass.getPackage();
Class superclass = aClass.getSuperclass();
Class[] interfaces = aClass.getInterfaces();
Constructor[] constructors = aClass.getConstructors();
Method[] method = aClass.getMethods();
Field[] methods = aClass.getFields();

Annotation[] annotations = aClass.getAnnotations();

No comments:

Post a Comment

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