Home > Java > JavaBase > Detailed introduction to java reflection mechanism

Detailed introduction to java reflection mechanism

Release: 2019-11-27 13:58:14
forward
2241 people have browsed it

Detailed introduction to java reflection mechanism

1. What is JAVA’s reflection mechanism (recommended: java video tutorial)

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:

Detailed introduction to java reflection mechanism

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:

Call getClass:

Boolean var1 = true;
Class<?> classType2 = var1.getClass();
System.out.println(classType2);
Copy after login

Output: class java.lang.Boolean

Use .class syntax :

Class<?> classType4 = Boolean.class;
System.out.println(classType4);
Copy after login

Output: class java.lang.Boolean

Use static method Class.forName():

Class<?> classType5 = Class.forName("java.lang.Boolean");
System.out.println(classType5);
Copy after login

Output: class java.lang.Boolean

Use the TYPE syntax of primitive wrapper classes:

The primitive type returned here is different from that returned by Boolean.class

Class<?> classType3 = Boolean.TYPE;
System.out.println(classType3);
Copy after login

Output: boolean

2. Get the Fields of the 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 getDeclaredField(String name)Returns a Field object that reflects the specified declared field of the class or interface represented by this Class objectpublic 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()

private void com.quincy.ExtendType.Log(java.lang.String)

public void com.quincy.ExtendType.setIntExtendField(int)

public int com.quincy.ExtendType.getIntExtendField()

4、获取类的Constructor

通过反射机制得到某个类的构造器,然后调用该构造器创建该类的一个实例

Class类提供了几个方法获取类的构造器。

public Constructor<T> getConstructor(Class<?>... parameterTypes)
Copy after login

返回一个 Constructor 对象,它反映此 Class 对象所表示的类的指定公共构造方法

public Constructor<?>[] getConstructors()
Copy after login

返回一个包含某些 Constructor 对象的数组,这些对象反映此 Class 对象所表示的类的所有公共构造方法

public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
Copy after login

返回一个 Constructor 对象,该对象反映此 Class 对象所表示的类或接口的指定构造方法

public Constructor<?>[] getDeclaredConstructors()
Copy after login

返回 Constructor 对象的一个数组,这些对象反映此 Class 对象表示的类声明的所有构造方法。它们是公共、保护、默认(包)访问和私有构造方法

// 使用getConstructors获取构造器  
Constructor<?>[] constructors = classType.getConstructors();
for (Constructor<?> m : constructors)
{
    System.out.println(m);
}
             
System.out.println();
             
// 使用getDeclaredConstructors获取构造器   
constructors = classType.getDeclaredConstructors();
for (Constructor<?> m : constructors)
{
    System.out.println(m);
}
 
输出:
public com.quincy.ExtendType()
 
public com.quincy.ExtendType()
com.quincy.ExtendType(int,java.lang.String)
Copy after login

5、新建类的实例

通过反射机制创建新类的实例,有几种方法可以创建

调用无自变量ctor:

1、调用类的Class对象的newInstance方法,该方法会调用对象的默认构造器,如果没有默认构造器,会调用失败.

Class<?> classType = ExtendType.class;
Object inst = classType.newInstance();
System.out.println(inst);
Copy after login

输出:

Type:Default Constructor

ExtendType:Default Constructor

com.quincy.ExtendType@d80be3

2、调用默认Constructor对象的newInstance方法

Class<?> classType = ExtendType.class;
Constructor<?> constructor1 = classType.getConstructor();
Object inst = constructor1.newInstance();
System.out.println(inst);
Copy after login

输出:

Type:Default Constructor

ExtendType:Default Constructor

com.quincy.ExtendType@1006d75

调用带参数ctor:

3、调用带参数Constructor对象的newInstance方法

Constructor<?> constructor2 =
classType.getDeclaredConstructor(int.class, String.class);
Object inst = constructor2.newInstance(1, "123");
System.out.println(inst);
Copy after login

输出:

Type:Default Constructor

ExtendType:Constructor with parameters

com.quincy.ExtendType@15e83f9

6、调用类的函数

通过反射获取类Method对象,调用Field的Invoke方法调用函数。

Class<?> classType = ExtendType.class;
Object inst = classType.newInstance();
Method logMethod = classType.<strong>getDeclaredMethod</strong>("Log", String.class);
logMethod.invoke(inst, "test");
 
输出:
Type:Default Constructor
ExtendType:Default Constructor
<font color="#ff0000">Class com.quincy.ClassT can not access a member of class com.quincy.ExtendType with modifiers "private"</font>
 
<font color="#ff0000">上面失败是由于没有权限调用private函数,这里需要设置Accessible为true;</font>
Class<?> classType = ExtendType.class;
Object inst = classType.newInstance();
Method logMethod = classType.getDeclaredMethod("Log", String.class);
<font color="#ff0000">logMethod.setAccessible(true);</font>
logMethod.invoke(inst, "test");
Copy after login

7、设置/获取类的属性值

通过反射获取类的Field对象,调用Field方法设置或获取值

Class<?> classType = ExtendType.class;
Object inst = classType.newInstance();
Field intField = classType.getField("pubIntExtendField");
intField.<strong>setInt</strong>(inst, 100);
    int value = intField.<strong>getInt</strong>(inst);
Copy after login

四、动态创建代理类

代理模式:代理模式的作用=为其他对象提供一种代理以控制对这个对象的访问。

代理模式的角色:

抽象角色:声明真实对象和代理对象的共同接口

代理角色:代理角色内部包含有真实对象的引用,从而可以操作真实对象。

真实角色:代理角色所代表的真实对象,是我们最终要引用的对象。

动态代理:

java.lang.reflect.Proxy:

Proxy 提供用于创建动态代理类和实例的静态方法,它还是由这些方法创建的所有动态代理类的超类

InvocationHandler:

是代理实例的调用处理程序 实现的接口,每个代理实例都具有一个关联的调用处理程序。对代理实例调用方法时,将对方法调用进行编码并将其指派到它的调用处理程序的 invoke 方法。

动态Proxy是这样的一种类:

它是在运行生成的类,在生成时你必须提供一组Interface给它,然后该class就宣称它实现了这些interface。你可以把该class的实例当作这些interface中的任何一个来用。当然,这个Dynamic Proxy其实就是一个Proxy,它不会替你作实质性的工作,在生成它的实例时你必须提供一个handler,由它接管实际的工作。

在使用动态代理类时,我们必须实现InvocationHandler接口

步骤:

1、定义抽象角色

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());
Copy after login

5、通过调用代理对象的方法去调用真实角色的方法。

sub.Request();
Copy after login

输出:

class $Proxy0 新建的代理对象,它实现指定的接口

Method:public abstract void DynamicProxy.Subject.Request(),Args:null
Copy after login

RealSubject 调用的真实对象的方法

更多java知识请关注java基础教程栏目。

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!

Related labels:
source:cnblogs.com
Statement of this 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
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