Java reflection is Java regarded as dynamic (or quasi- dynamic) a key property of languages. This mechanism allows the program to obtain the internal information of any class with a known name through the Reflection APIs at runtime, including its modifiers (such as public, static, etc.), superclass (such as Object), implemented interfaces (such as Cloneable), as well as All information about fields and methods, and can change the contents of fields or invoke methods at runtime.
The Java reflection mechanism allows the program to load, detect, and use classes that are completely unknown during compilation at runtime.
In other words, Java can load a class whose name is known only at runtime and obtain its complete structure.
2. Reflection API provided in JDK
The API related to Java reflection is in the package java.lang.reflect. The reflect package of JDK 1.6.0 is as shown below:
Member interface
This interface can obtain information about the class members (fields or methods) and the latter constructor.
AccessibleObject class
This class is the base class for domain objects, method objects, and constructor objects. It provides the ability to mark reflected objects as suppressing default Java language access control checks when used.
Array class
This class provides methods to dynamically generate and access JAVA arrays.
Constructor class
Provides information about the constructor of a class and an interface for accessing the constructor of the class.
Field class
Provides field information of a class and an interface for accessing the field of the class.
Method class
Provides method information of a class and an interface for accessing the methods of the class.
Modifier class
Provides static methods and constants to decode class and member access modifiers.
Proxy class
Provides static methods to dynamically generate proxy classes and class instances.
3. What functions does the JAVA reflection mechanism provide?
The Java reflection mechanism provides the following functions:
Determine the class to which any object belongs at run time
At run time Construct an object of any class
Judge the member variables and methods of any class at runtime
Call the method of any object at runtime
At runtime When creating a new class object
When using Java's reflection function, you must first obtain the Class object of the class, and then obtain other objects through the Class object.
Here we first define the class used for testing:
class Type{
public int pubIntField;
public String pubStringField;
private int prvIntField;
public Type(){
Log("Default Constructor");
}
Type(int arg1, String arg2){
pubIntField = arg1;
pubStringField = arg2;
Log("Constructor with parameters");
}
public void setIntField(int val) {
this.prvIntField = val;
}
public int getIntField() {
return prvIntField;
}
private void Log(String msg){
System.out.println("Type:" + msg);
}
}
class ExtendType extends Type{
public int pubIntExtendField;
public String pubStringExtendField;
private int prvIntExtendField;
public ExtendType(){
Log("Default Constructor");
}
ExtendType(int arg1, String arg2){
pubIntExtendField = arg1;
pubStringExtendField = arg2;
Log("Constructor with parameters");
}
public void setIntExtendField(int field7) {
this.prvIntExtendField = field7;
}
public int getIntExtendField() {
return prvIntExtendField;
}
private void Log(String msg){
System.out.println("ExtendType:" + msg);
}
}
Copy after login
1. Obtain the Class object of the class
The instance of the Class class represents the class and class in the running Java application. interface. There are many ways to obtain the Class object of a class:
You can get an attribute of a class through the reflection mechanism, and then change the field corresponding to an instance of this class. The value of this property. JAVA's Class class provides several methods to obtain the attributes of the class.
public Field getField(String name)
Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object
public Field[] getFields()
Returns an array containing certain Field objects that reflect all accessible properties of the class or interface represented by this Class object Public Field
##public Field getDeclaredField(String name)
Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object
public Field[] getDeclaredFields()
Returns an array of Field objects that reflect all fields declared by the class or interface represented by this Class object
Class<?> classType = ExtendType.class;
// 使用getFields获取属性
Field[] fields = classType.getFields();
for (Field f : fields)
{
System.out.println(f);
}
System.out.println();
// 使用getDeclaredFields获取属性
fields = classType.getDeclaredFields();
for (Field f : fields)
{
System.out.println(f);
}
Copy after login
输出:
public int com.quincy.ExtendType.pubIntExtendField
public java.lang.String com.quincy.ExtendType.pubStringExtendField
public int com.quincy.Type.pubIntField
public java.lang.String com.quincy.Type.pubStringField
public int com.quincy.ExtendType.pubIntExtendField
public java.lang.String com.quincy.ExtendType.pubStringExtendField
private int com.quincy.ExtendType.prvIntExtendField
可见getFields和getDeclaredFields区别:
getFields返回的是申明为public的属性,包括父类中定义,
getDeclaredFields返回的是指定类定义的所有定义的属性,不包括父类的。
3、获取类的Method
通过反射机制得到某个类的某个方法,然后调用对应于这个类的某个实例的该方法
Class类提供了几个方法获取类的方法。
public Method getMethod(String name, Class<?>... parameterTypes)
Copy after login
返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法
public Method[] getMethods()
Copy after login
返回一个包含某些 Method 对象的数组,这些对象反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法
public Method getDeclaredMethod(String name,Class<?>... parameterTypes)
Copy after login
返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法
public Method[] getDeclaredMethods()
Copy after login
返回 Method 对象的一个数组,这些对象反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法
// 使用getMethods获取函数
Class<?> classType = ExtendType.class;
Method[] methods = classType.getMethods();
for (Method m : methods)
{
System.out.println(m);
}
System.out.println();
// 使用getDeclaredMethods获取函数
methods = classType.getDeclaredMethods();
for (Method m : methods)
{
System.out.println(m);
}
Copy after login
输出:
public void com.quincy.ExtendType.setIntExtendField(int)
public int com.quincy.ExtendType.getIntExtendField()
public void com.quincy.Type.setIntField(int)
public int com.quincy.Type.getIntField()
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
public interface Subject {
public void Request();
}
Copy after login
2、定义真实角色
public class RealSubject implements Subject {
@Override
public void Request() {
// TODO Auto-generated method stub
System.out.println("RealSubject");
}
}
Copy after login
3、定义代理角色
public class DynamicSubject implements InvocationHandler {
private Object sub;
public DynamicSubject(Object obj){
this.sub = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("Method:"+ method + ",Args:" + args);
method.invoke(sub, args);
return null;
}
}
Copy after login
4、通过Proxy.newProxyInstance构建代理对象
RealSubject realSub = new RealSubject();
InvocationHandler handler = new DynamicSubject(realSub);
Class<?> classType = handler.getClass();
Subject sub = (Subject)Proxy.newProxyInstance(classType.getClassLoader(),
realSub.getClass().getInterfaces(), handler);
System.out.println(sub.getClass());
The above is the detailed content of Detailed introduction to java reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn