Three very interesting sites are recommended first:
http://www.programcreek.com/simple-java/
http://tutorials.jenkov.com/
http://www.meetup.com/
Java Reflection makes it 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.
Classes
From the classes you can obtain information about:
- Class Name
- Class modifies (public, private, synchronized etc.)
- Package Info
- Superclass
- Implemented Interfaces
- Constructors
- Methods
- Fields
- Annotations
Before doing any action, you must obtainjava.lang.Class对象。Java中所有类型,包括基础类型,数组,都有关联的class对象。获取class的方式
1) If you know the class name at compile time: myclass.class
2) If the class name is not known at compile time but can get the string at run time: Class.forName ("...")//If not found in classpath, it will be thrown classnotfoundexception
Class Name
String className = Aclass.getname (); Get the full name of the class, including the package name
String className = Aclass.getsimplename (); Package name not included
Class Modifiers
You can access the class's modifiers through the class object, modifiers are: public,private,static, and so on.
int modifiers = Aclass.getmodifiers (); int type
modifier.isabstract (int modifiers); View by Modifier.xxx
Package Name
Package package = Aclass.getpackage ();
The package object provides access to the package's information.
Superclass
Class superclass = Aclass.getsuperclass ();
The superclass object is a class object.
Implementing interfaces
Class[] interfaces = Aclass.getinterfaces ();
If you want to get all the interfaces implemented by the class, you have to recursively traverse the parent node object
Constructors
Get Constructor object:
Constructor[] Constructors = aclass.getconstructors (); // Get all public = aclass.getconstructor (new class[]{string. Class/ / Gets the public constructor with a string parameter , if no matching constructor is found, Will throw Nosuchmethodexception
Get the constructor parameter:
class[] parametertypes = Constructor.getparametertypes ();
Instantiate constructor:
MyObject MyObject = (MyObject) constructor.newinstance ("Constructor-arg1");
Methods
To access the public method only:
Class.getMethod(String name, Class[] parameterTypes)And Class.getMethods() returns only public methods. Like what:
New Class[]{string. Class/get method that takes a String as argumentmethod = MyObject. class. GetMethod ("DoSomething", String. Class// If it is a static method, MyObject is replaced by null
访问private方法:
调用 Class.getDeclaredMethod(String name, Class[] parameterTypes)OrClass.getDeclaredMethods()方法。比如:
New Privateobject ("The Private Value"= privateobject. Class. Getdeclaredmethod (null); privatestringmethod.setaccessible ( true ); = (String) null);
By calling your Method.setAcessible(true) turn off the access checks for this particular Method instance, for reflectiononly.
Fields
To access public fields:
Called Class.getField(String name) 和Class.getFields()方法只返回public fields。
Visit Privatefields:
Need to call Class.getDeclaredField(String name) orClass.getDeclaredFields()方法。例如:
New Privateobject ("The Private Value"= privateobject. Class. Getdeclaredfield ("privatestring"); privatestringfield.setaccessible ( true ); = (String) privatestringfield.get (privateobject);
By calling your Field.setAcessible(true) turn off the access checks for this particular Field instance, for reflection only.
Annotations
annotation[] annotations = aclass.getannotations ();
Annotations are the new feature introduced in Java 5, which is a comment or meta-data inserted into Java code. Annotations can be processed by the compilation tool at compile time, or by Java reflection at run time.
For example, class Theclass have annotations @MyAnnotation . Annotations are defined like interfaces. The in @ front of the interface marks it as an annotation.
@MyAnnotation (name= "Somename", value = "Hello World")publicclass Theclass {}
@Retention (retentionpolicy.runtime) @Target (elementtype.type) public @Interface myannotation { public String name (); Public String value ();}
There are two instructions (directives) in the annotation definition above:
@Retention(RetentionPolicy.RUNTIME)means that the annotation can is accessed via reflection at runtime. If you don't set this directive, the annotation is not being preserved at runtime, and thus not available via reflection.
@Target(ElementType.TYPE)means that the annotation can is only used ontop of types (classes and interfaces typically). can also specify METHOD or FIELD , or can leave the target out alltogether so the annotation can is used for both CL Asses, methods and fields.
Generics
Many forum articles say that Java generic information will be erased at compile time, but this is not entirely true. The case of running Java generics can be broadly divided into two categories:
- Declaring a class/interface as being parameterizable.
- Using a parameterizable class.
We can get the return type of the generic function, the parameter type, the fields type
Arrays
Working with arrays via Java Reflection are done using the java.lang.reflect.Array class.
Create Array: int[] Intarray = (int[]) array.newinstance (Int.class, 3);
access to array: This is done via the and Array.get(...) Array.set(...) methods.
gets the class object of the array :
Class Stringarrayclass = string[]. class // for the base type array, the shorthand for "I" is only applicable to the array condition Class Stringarrayclass = Class.forName ("[ Ljava.lang.String; "); // for object Arrays
Dynamic Agent *
You create dynamic proxies using the Proxy.newProxyInstance() method. The newProxyInstance() methods takes 3 parameters:
ClassLoaderthe. is to "load" the dynamic proxy class.
- An array of interfaces to implement.
InvocationHandlerforward all methods calls on the proxy to.
For example:
New= (myinterface) proxy.newproxyinstance ( myinterface. class . getClassLoader (), New Class[] {myinterface. Class }, handler);
Class Loading & reloading*
All classes in a Java application is loaded using some subclass ofjava.lang.ClassLoader
Dynamic class loading: It's easy to load classes dynamically, we just need to get one ClassLoader and then callloadClass()方法
public class MainClass { static void main (string[] args) { ClassLoader ClassLoader = MainClass. class .getclassloader (); try {Class AClass = classloader.l Oadclass ("Com.jenkov.MyClass" ); System.out.println ( aclass.getname () = "+ Aclass.getname ()); catch (ClassNotFoundException e) {E.PR Intstacktrace (); }}
Dynamic class Reload: Reloads a more complex point because Java loads a class to check whether the class is loaded. It is not possible to implement overloading with Java Buildin ClassLoader. To achieve this, you must implement ClassLoader yourself.
Todo
[Java] Java Reflection