reflection
Class itself is a class
Class object can only be created by the system
How reflection is achieved
the way | Demo |
---|---|
Obtain by object | User user = new User(); Class c1 = user.getClass() |
Through the forName() static method of the Class class | Class c2 = Class.forName(“com.radish.domain.User”); |
By class name.class | Class c3 = User.class |
Code demo:
public stati void main(String[] args) {
// 方式一:使用对象
User user = new User();
Class c1 = user.getClass();
// 方式二:使用Class的静态方法forName()
Class c2 = Class.forName("com.radish.User");
// 方式三:使用类的.class
Class c3 = User.class;
}
Commonly used methods in reflection
- Create an instance object
- Get field, field attributes
- Get method, method attribute
- Constructor etc.
Method name | Features |
---|---|
newInstance | Equivalent to using a parameterless constructor new an object |
getConstructor | Get the constructor object of the object |
getMethods / getDeclaredMethods | Get the method object array. The method without Declared can get the methods of this class and the parent class, but public must be used. The method with Declared can only get all methods of this class, including (private, protect, public) |
getMethod / getDeclaredMethod | Get a specified method by specifying the method name, Declared has the same effect as above |
getFields / getDeclaredFields | Get the fields in the class and return a Filed array. The function of Declared is the same as above |