Reflection is an API used to inspect and manipulate classes. The package is java.lang.reflect
Here are some things you can do with it.
You can get the class name:
String name = Integer.class.getName(); System.out.println(name);
Get the superclass name:
String superclassName = Integer.class.getSuperclass().getName(); System.out.println(superclassName);
Check the access modifier of the class:
int modifier = Integer.class.getModifiers(); System.out.println(Modifier.isPublic(modifier));
Get the method names:
Method[] methods = Integer.class.getMethods(); for (Method method : methods) System.out.println(method.getName());
Get the method's return type:
Method[] methods = Integer.class.getMethods(); for (Method method : methods) System.out.println(method.getReturnType());
Get the method's parameters:
Method[] methods = Integer.class.getMethods(); for (Method method : methods) { Class<?>[] params = method.getParameterTypes(); for (Class<?> param : params) System.out.println(param.getName()); }
Get the constructor:
Constructorconstructor = String.class.getConstructor();
Get a constructor with parameters:
Constructorconstructor = String.class.getConstructor(new Class[] {String.class});
Run a constructor:
Constructorconstructor = String.class.getConstructor(new Class[] {String.class}); String str = constructor.newInstance("example"); System.out.println(str);
Access a private member variable:
Integer i = new Integer(6); Field field = Integer.class.getDeclaredField("value"); field.setAccessible(true); int value = (int) field.get(i);
Invoke a method:
String str = "example"; Method method = String.class.getDeclaredMethod("hashCode"); System.out.println(method.invoke(str));
Invoke a method with parameters:
String str = "example"; Method method = String.class.getDeclaredMethod( "equalsIgnoreCase", String.class); System.out.println(method.invoke( str, new Object[] {new String("example")}));
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.