JAVA语言的反射机制

版权声明:仅供学习,谢谢 https://blog.csdn.net/weixin_43907332/article/details/86061673

Java语言的反射机制

在Java 运行时环境中,对于任意一个类,能否知道这个类有哪些属性和方法?对于任意一个对象,能否调用它的任意一个方法?答案是肯定的。这种动态获取类的信息以及动态调用对象的方法的功能来自于Java 语言的反射(Reflection)机制。

Java 反射机制主要提供了以下功能:
在运行时判断任意一个对象所属的类。
在运行时构造任意一个类的对象。
在运行时判断任意一个类所具有的成员变量和方法。
在运行时调用任意一个对象的方法。

Reflection 是Java被视为动态(或准动态)语言的一个关键性质。这个机制允许程序在运行时透过Reflection APIs取得任何一个已知名称的class的内部信息,包括其modifiers(诸如public, static 等等)、 superclass(例如Object)、实现之interfaces(例如Serializable),也包括fields和methods的所有信息,并可于运行时改变fields内容或调用methods。

一般而言,开发者社群说到动态语言,大致认同的一个定义是: “程序运行时,允许改变程序结构或变量类型,这种语言称为动态语言” 。从这个观点看, Perl, Python, Ruby是动态语言, C++, Java, C#不是动态语言

尽管在这样的定义与分类下Java不是动态语言,它却有着一个非常突出的动态相关机制:Reflection。这个字的意思是“反射、映象、倒影” ,用在Java身上指的是我们可以于运行时加载、探知、使用编译期间完全未知的classes。换句话说, Java程序可以加载一个运行时才得知名称的class,获悉其完整构造(但不包括methods定义),并生成其对象实体、或对其fields设值、或唤起其methods。这种“看透class”的能力(the ability of the program to examine itself)被称为introspection(内省、内观、反省)。 Reflection和introspection是常被并提的两个术语。

在JDK中,主要由以下类来实现Java反射机制,这些类都位于java.lang.reflect包中(除了Class,位于java.lang包中)
– Class类:代表一个类。
– Field 类:代表类的成员变量(成员变量也称为类的属性)。
– Method类:代表类的方法。
– Constructor 类:代表类的构造方法。
– Array类:提供了动态创建数组,以及访问数组的元素的静态方法

例程DumpMethods类演示了Reflection API的基本作用,它读取命令行参数指定的类名,然后打印这个类所具有的方法信息

package sixtyFirst;

import java.lang.reflect.Method;

public class DumpMethods {

	public static void main(String[] args) throws Exception{
		
		//Class<?> classType = Class.forName("java.lang.String");
        //运行期的行为
		Class<?> classType = Class.forName(args[0]);
		Method[] methods = classType.getDeclaredMethods();
		//反应出java.lang.String中的所有方法的信息,以Method[]的形式返回
		for(Method method : methods) {
			System.out.println(method);
		}
		
	}

}

args[0]是java.lang.Object
结果是:
protected void java.lang.Object.finalize() throws java.lang.Throwable
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 final native void java.lang.Object.wait(long) 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()
protected native java.lang.Object java.lang.Object.clone() throws java.lang.CloneNotSupportedException
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
private static native void java.lang.Object.registerNatives()

Java 中,无论生成某个类的多少个对象,这些对象都会对应于同一个 Class 对象。

例程ReflectTester 类进一步演示了ReflectionAPI的基本使用方法。 ReflectTester类有一个copy(Object object)方法,这个方法能够创建一个和参数object 同样类型的对象,然后把object对象中的所有属性拷贝到新建的对象中,并将它返回。

package sixtyFirst;

import java.lang.reflect.Method;

public class InvokeTester {

	public int add(int param1, int param2) {
		return param1 + param2;
	}
	
	public String echo(String message) {
		return "hello : " + message;
	}
	
	public static void main(String[] args) throws Exception {
		InvokeTester tester = new InvokeTester();
		System.out.println(tester.add(1,2));
		System.out.println(tester.echo("tom"));
		
		System.out.println("-----------------");
		
		Class<?> classType = InvokeTester.class;
		
		Object invokeTester = classType.newInstance();//声明InvokeTester的实例
		
		System.out.println(invokeTester instanceof InvokeTester);
		
		System.out.println("-----------------");
		
		Method addMethod = classType.getMethod("add", new Class[] {int.class, int.class});//获取某个方法,java中有重载,所以需要方法名,和传入的参数的具体类型
		
		Object result = addMethod.invoke(invokeTester, new Object[] {1, 2});//invoke方法是用来调用目标方法,1和2自动装箱。
	    //如果Object数组中不放整形变量而放其他类型,例如String,在编译期间不会报错,但是在运行期间就会报错,因为String不能转换为int。
	    System.out.println((Integer)result);
	    
	    Method echoMethod = classType.getMethod("echo", new Class[] {String.class});
	    
	    Object result2 = echoMethod.invoke(invokeTester, new Object[] {"tom"});
		
		System.out.println((String)result2);
		
	}
	
}

结果是:
3
hello : tom


true


3
hello : tom

Class类、Method类及Field类的使用方式及深度探析

  1. 要想使用反射,首先需要获得待处理类或对象所对应的 Class 对象。

Object类中的 getclass方法

public final Class<?> getClass()
(无法被重写的方法,会返回一个Class对象)
Returns the runtime class of this Object.
(返回这个对象运行时的class)

  1. 获取某个类或某个对象所对应的 Class 对象的常用的 3 种方式:以String举例
    a) 使用 Class 类的静态方法 forName :Class.forName(“java.lang.String”);
    b) 使用类的.class 语法: String.class;
    c) 使用对象的 getClass()方法: String s=“aa”; Class<?> clazz = s.getClass();
    例子ReflectTester 类进一步演示了ReflectionAPI的基本使用方法。 ReflectTester类有一个copy(Object object)方法,这个方法能够创建一个和参数object 同样类型的对象,然后把object对象中的所有属性拷贝到新建的对象中,并将它返回。

这个例子只能复制简单的JavaBean,假定JavaBean 的每个属性都有public 类型的getXXX()和setXXX()方法。

package sixtySecound;


public class ReflectTester {

	//该方法实现对Custom对象的拷贝操作
	public Object copy(Object object) {
		Class<?> classType = object.getClass();
		
		System.out.println(classType);
		
		return null;
	}
	public static void main(String[] args) {
		
		ReflectTester test = new ReflectTester();
		
		test.copy(new Customer());
	}
}

class Customer{
	private Long id;
	private String name;
	private int age;
	
	public Customer() {
		
	}
	
	public Customer(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

结果是:
class sixtySecound.Customer
将copy里的输出替换为如下代码:

System.out.println(classType.getName());

结果是:
sixtySecound.Customer
获取了Customer从属的类的全称

Class类中的newInstance方法

public T newInstance() throws InstantiationException, IllegalAccessException
Creates a new instance of the class represented by this Class object.
(创建一个新的目标类的实例通过Class对象)
The class is instantiated as if by a new expression with an empty argument list.
(这个类被实例化,好像通过一个new的表达式并且使用一个空的参数列表来实例化一样)
The class is initialized if it has not already been initialized.
(如果尚未初始化,则初始化该类)
要想声明一个对象必须要通过他的构造方法生成,反射中存在一个叫Constructor的类,这个Constructor类是构造方法所对应的Constructor对象。

Constructor

java.lang.reflect Class Constructor
Constructor位于java.lang.reflect包下。

newInstance方法

public T newInstance(Object… initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException

通过class对象调用getConstructor方法来获得Construcor的方法
public Constructor getConstructor(Class<?>… parameterTypes) throws NoSuchMethodException, SecurityException

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
(返回一个Constructor对象,该对象反映此Class对象所表示的类的指定public构造方法。)

        Class<?> classType = object.getClass();
		
		Constructor cons = classType.getConstructor(new Class[] {});
		Object obj = cons.newInstance(new Object[] {});
		//上面两行代码等价于下面一行
		Object obj2 = classType.newInstance();

虽然效果一样但是下面的语句有局限性,如果想要通过带参数的构造方法创建对象,还是需要用上面的两行。

  1. 若想通过类的不带参数的构造方法来生成对象,我们有两种方式:
    a) 先获得 Class 对象,然后通过该 Class 对象的 newInstance()方法直接生成即可:
    Class<?> classType = String.class;
    Object obj = classType.newInstance();
    b) 先获得 Class 对象,然后通过该对象获得对应的 Constructor 对象,再通过该Constructor对象的 newInstance()方法生成:
    Class<?> classType = Customer.class;
    Constructor cons = classType.getConstructor(new Class[]{});
    Object obj = cons.newInstance(new Object[]{});
        Constructor cons = classType.getConstructor(new Class[]{String.class, int.class});
		
		Object obj = cons.newInstance(new Object[] {"hello", 3});
  1. 若想通过类的带参数的构造方法生成对象,只能使用下面这一种方式:
    Class<?> classType = Customer.class;
    Constructor cons = classType.getConstructor(new Class[]{String.class, int.class});
    Object obj = cons.newInstance(new Object[]{“hello”, 3});

Class类中的getDeclaredFields方法

public Field[] getDeclaredFields() throws SecurityException
(获取一个Field类型的数组,Field代表成员变量,所有这个方法会返回所有的成员变量)
Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

package sixtySecound;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectTester {

	// 该方法实现对Custom对象的拷贝操作
	public Object copy(Object object) throws Exception {
		
		Class<?> classType = object.getClass();

		Object objectCopy = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});
		//声明一个对象
		Field[] fields = classType.getDeclaredFields();
		//获得对象的所有成员变量
		
		for(Field field : fields) {
			String name = field.getName();
			
			String firstLetter = name.substring(0 , 1).toUpperCase();//将属性的首字母大写
			//包含0,不包含1,所以取得是第0个字符
			String getMethodName = "get" + firstLetter + name.substring(1);//获取get方法名
			String setMethodName = "set" + firstLetter + name.substring(1);//获取set方法名
			
			Method getMethod = classType.getMethod(getMethodName, new Class[] {});
			Method setMethod = classType.getMethod(setMethodName, new Class[]{field.getType()});
			
			Object value = getMethod.invoke(object, new Object[] {});
			
			setMethod.invoke(objectCopy, new Object[] {value});
			
		}
		
		/*
		 * Constructor cons = classType.getConstructor(new Class[]{String.class,
		 * int.class});
		 * 
		 * Object obj = cons.newInstance(new Object[] {"hello", 3}); //上面两行代码等价于下面一行
		 * Object obj2 = classType.newInstance();
		 * 
		 * System.out.println(obj);
		 */

		return objectCopy;
	}

	public static void main(String[] args) throws Exception {

		Customer customer = new Customer("Tom", 20);
		customer.setId(1L);//customer.setId(new Long(1));
		
		ReflectTester test = new ReflectTester();

		Customer customer2 = (Customer)test.copy(customer);
		
		System.out.println(customer2.getId() + "," + customer2.getName() + "," + customer2.getAge());
	}
}

class Customer {
	private Long id;
	private String name;
	private int age;

	public Customer() {

	}

	public Customer(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

ReflectTester 类的copy(Object object)方法
依次执行以下步骤

  • 获得对象的类型:
    – Class classType=object.getClass();
    – System.out.println(“Class:”+classType.getName());
    在java.lang.Object 类中定义了getClass()方法,因此对于任意一个Java对象,都可以通过此方法获得对象的类型。 Class类是Reflection API中的核心类,它有以下方法
    – getName():获得类的完整名字。
    – getFields():获得类的public类型的属性。
    – getDeclaredFields():获得类的所有属性。
    – getMethods():获得类的public类型的方法。
    – getDeclaredMethods():获得类的所有方法。
    getMethod(String name, Class[] parameterTypes):获得类的特定方法, name参数指定方法的名字, parameterTypes 参数指定方法的参数类型。
    • getConstructors():获得类的public类型的构造方法。
    • getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。
    • newInstance():通过类的不带参数的构造方法创建这个类的一个对象
  • 通过默认构造方法创建一个新对象:
    • Object
    objectCopy=classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
    • 以上代码先调用Class类的getConstructor()方法获得一个Constructor 对象, 它代表默认的构造方法,然后调用Constructor对象的newInstance()方法构造一个实例。
  • 获得对象的所有属性:
    Field fields[]=classType.getDeclaredFields();
    Class 类的getDeclaredFields()方法返回类的所有属性,包括public ,protected ,默认,private访问级别的属性
  • 获得每个属性相应的getXXX()和setXXX()方法,然后执行这些方法,把原来对象的属性拷贝到新的对象中。

java.lang.Array 类

提供了动态创建和访问数组元素的各种静态方法。

ArrayTester1 类的main()方法创建了一个长度为10 的字符串数组,接着把索引位置为5 的元素设为“hello”,然后再读取索引位置为5 的元素的值

package sixtyThird;

import java.lang.reflect.Array;

public class ArrayTester1 {

	public static void main(String[] args) throws Exception{
		Class<?> classType = Class.forName("java.lang.String");
		
		Object array = Array.newInstance(classType, 10);
		
		Array.set(array, 5, "hello");
		
		String str = (String)Array.get(array, 5);
		
		System.out.println(str);
	}
}

结果是:
hello

Array类中的newInstance

public static Object newInstance(Class<?> componentType, int… dimensions) throws IllegalArgumentException, NegativeArraySizeException

Creates a new array with the specified component type and dimensions. If componentType represents a non-array class or interface, the new array has dimensions.length dimensions and componentType as its component type. If componentType represents an array class, the number of dimensions of the new array is equal to the sum of dimensions.length and the number of dimensions of componentType. In this case, the component type of the new array is the component type of componentType.
The number of dimensions of the new array must not exceed 255.

(创建具有指定组件类型和维度的新数组。 如果componentType表示非数组类或接口,则新数组将dimension.length维度和componentType作为其组件类型。 如果componentType表示数组类,则新数组的维数等于dimension.length和componentType的维数。 在这种情况下,新数组的组件类型是componentType的组件类型。
新数组的维度数不得超过255。)
组件类型:举个简单的例子有助于理解,一个一维数组,每一个元素是一个int类型,这个int是component type,而对于一个二维数组,每一个元素都是一个一维数组,这个一维数组就是component type。

  1. Integer.TYPE 返回的是 int,而 Integer.class 返回的是 Integer 类所对应的 Class 对象。
  2. Class类中有getComponentType,它可以返回这个Class代表的数组的组件类型。
    public Class<?> getComponentType()
    Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.

例子ArrayTester2 类的main()方法创建了一个 5 x 10 x 15 的整型数组,并把索引位置为[3][5][10] 的元素的值为设37。

package sixtyThird;

import java.lang.reflect.Array;

public class ArratTester2 {

	public static void main(String[] args) {

		int[] dims = new int[] { 5, 10, 15 };

		Object array = Array.newInstance(Integer.TYPE, dims);//生成一个三维数组[5][10][15]
		//Object array = Array.newInstance(Intefer.TYPE, 5,10,15);这个和上句表达的是一样的意思。

        Class<?> classType = array.getClass().getComponentType();
		
		System.out.println(classType);
		
		Object arrayObj = Array.get(array, 3);
		
        classType = arrayObj.getClass().getComponentType();
		
		System.out.println(classType);
		
		arrayObj = Array.get(arrayObj, 5);
		
		classType = arrayObj.getClass().getComponentType();
			
		System.out.println(classType);
		
		Array.setInt(arrayObj, 10, 37);
		
		classType = String.class.getComponentType();
		
		System.out.println(classType);
		
		int[][][] arrayCast = (int[][][])array;
		
		System.out.println(arrayCast[3][5][10]);
		
		
		
		/*
		 * System.out.println(Integer.TYPE); 
		 * 返回int,所以8个包装类的TYPE方法返回的是原生数据类型的Class对象
		 * System.out.println(Integer.class);
		 * 返回class java.lang.Integer,返回Integer这个类型所对应的Class对象
		 */
	}
}

结果是:
class [[I
class [I
int
null
37

Class类中的getMethod方法

public Method getMethod(String name, Class<?>… parameterTypes) throws NoSuchMethodException, SecurityException
Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object. The name parameter is a String specifying the simple name of the desired method.

这个方法和getDeclaredMethod传入的参数相同返回类型相同,不同的是,只能返回public的方法,而getDeclaredMethod可以返回所有类型的方法。

Class AccessibleObject

java.lang.Object
java.lang.reflect.AccessibleObject

The AccessibleObject class is the base class for Field, Method and Constructor objects. It provides the ability to flag a reflected object as suppressing default Java language access control checks when it is used. The access checks–for public, default (package) access, protected, and private members–are performed when Fields, Methods or Constructors are used to set or get fields, to invoke methods, or to create and initialize new instances of classes, respectively.
(AccessibleObject类是Field,Method和Constructor对象的基类。 它提供了将反射对象标记为在使用时禁止默认Java语言访问控制检查的功能。 当使用Fields,Methods或Constructors设置或获取字段,调用方法或创建和初始化类的新实例时,将执行访问检查 - 对于公共,默认(包)访问,受保护和私有成员。 , 分别。)

setAccessible方法

public void setAccessible(boolean flag)
throws SecurityException
Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.
(将此对象的可访问标志设置为指示的布尔值。 值true表示反射对象在使用时应禁止Java语言访问检查。 值false表示反射对象应强制执行Java语言访问检查。)

package sixtyThird;

public class Private {

	private String sayHello(String name) {
		return "hello :" + name;
	}
}

package sixtyThird;

import java.lang.reflect.Method;

public class TestPrivate {

	public static void main(String[] args) throws Exception {
		Private p = new Private();
		
		Class<?> classType = p.getClass();
		
		Method method = classType.getDeclaredMethod("sayHello", String.class);
		
		method.setAccessible(true);//压制JAVA的访问控制检查
		
		String str = (String)method.invoke(p, "zhangsan");
		
		System.out.println(str);
		
	}
}

结果是:
hello :zhangsan

package sixtyFourth;
/**
 * 通过反射的形式将zhansan改为lisi并输出
 * @author LENOVO
 *
 */

public class Private2 {

	private String name = "zhangsan";
	
	public String getName() {
		return name;
	}
}

package sixtyFourth;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class TestPrivate2 {

	public static void main(String[] args) throws Exception{
		
		Private2 private2 = new Private2();

		Class<?> classType = private2.getClass();
		
		Field field = classType.getDeclaredField("name");
		
		field.setAccessible(true);//压制Java对访问修饰符的检查
		
		field.set(private2, "lisi");
		
		Method method = classType.getMethod("getName");
		
		System.out.println(private2.getName());
		System.out.println(method.invoke(private2));
		
	}
}


结果是:
lisi
lisi

“Class” class

  1. 众所周知Java有个Object class,是所有Java classes的继承根源,其内声明了数个应该在所有Java class中被改写的methods: hashCode()、 equals()、clone()、 toString()、 getClass()等。其中getClass()返回一个Class object。
  2. Class class十分特殊。它和一般classes一样继承自Object,其实体用以表达Java程序运行时的classes和interfaces,也用来表达enum、 array、 primitive、Java types
  3. (boolean, byte, char, short, int, long, float,double)以及关键词void。当一个class被加载,或当加载器(class loader)的defineClass()被JVM调用,JVM 便自动产生一个Class object。如果您想借由“修改Java标准库源码” 来观察Class object的实际生成时机(例如在Class的constructor内添加一个println()),不能够! 因为Class并没有public constructor
  4. Class是Reflection起源。针对任何您想探勘的class,唯有先为它产生一个Classobject,接下来才能经由后者唤起为数十多个的Reflection APIs

Class object 的取得途径

  1. Java允许我们从多种途径为一个class生成对应的Class object
Class object 诞生管道 示例
运用getClass()
注:每个class都有此函数
String str = "abc";
Class c1 = str.getClass();
运用
Class.getSuperclass()
Button b = new Button;
Class c1 = b.getClass();
Class c2 = c1.getSuperclass();
运用static method
Class.forName()
(最常被使用)
Class c1 = Class.forName("java.lang.String");
Class c2 = Class.forName("java.awt.Button");
Class c3 = Class.forName("java.util.LinkedList$Entry");
Class c4 = Class.forName("I");
Class c5 = Class.forName("[I");
运用
primitive wrapper
classes
的TYPE语法
Class c1 = Boolean.TYPE;返回的是boolean
Class c2 = Byte.TYPE; 相当于byte.class
Class c3 = Character.TYPE; 返回的是char
Class c4 = Short.TYPE; 返回的是short
Class c5 = Integer.TYPE;
Class c6 = Long.TYPE;
Class c7 = Float.TYPE;
Class c8 = Double.TYPE;
Class c9 = Void.TYPE;
package sixtyFifth;

public class ClassTest {

	public static void main(String[] args) {
		Class<?> classType = Child.class;
		
		System.out.println(classType);
		
		classType = classType.getSuperclass();
		
		System.out.println(classType);
		
        classType = classType.getSuperclass();
		
		System.out.println(classType);
		
        classType = classType.getSuperclass();
		
		System.out.println(classType);
	}
}

class Parent{
	
}

class Child extends Parent{
	
}

结果是:
class sixtyFifth.Child
class sixtyFifth.Parent
class java.lang.Object
null

运行时生成instances

欲生成对象实体,在Reflection 动态机制中有两种作法,一个针对“无自变量ctor”,一个针对“带参数ctor”。如果欲调用的是“带参数ctor“就比较麻烦些,不再调用Class的newInstance(),而是调用Constructor 的newInstance()。首先准备一个Class[]做为ctor的参数类型(本例指定为一个double和一个int),然后以此为自变量调用getConstructor(),获得一个专属ctor。接下来再准备一个Object[] 做为ctor实参值(本例指定3.14159和125),调用上述专属ctor的newInstance()。

Class c = Class.forName("DynTest");
Object obj = null;
obj = c.newInstance;//不带自变量
System.out.println(obj);

动态生成“Class object”所对应的class”的对象实体;无自变量

Class c = Class.forName("DynTest");
Class[] pTypes = new Class[]{doube.class, int.class};
Constructor ctor = c.getConstructor(pTypes);
//指定parameter list,便可获得特定的ctor

Object obj = null;
Object[] arg = new Object[]{3.14159, 125};//自变量
obj = ctor.newInstance(arg);
System.out.println(obj);
 动态生成“Class object对应的class”的对象实体;自变量以Object[]表示。

运行时调用methods

这个动作和上述调用“带参数之ctor”相当类似。首先准备一个Class[]做为参数类型(本例指定其中一个是String,另一个是Hashtable),然后以此为自变量调用getMethod(),获得特定的Method object。接下来准备一个Object[]放置自变量,然后调用上述所得之特定Method object的invoke()。

为什么获得Method object时不需指定回返类型?
因为method overloading机制要求signature必须唯一,而回返类型并非signature的一个成份。换句话说,只要指定了method名称和参数列,就一定指出了一个独一无二的method。

public String funs(String s, Hashtable ht){
    ...
    System.out.println("func invoked");
    return s;
}
public static void main(String args[]){
    Class c = Class.forName("Test");
    Class[] ptypes = new Class[2];
    ptypes[0] = Class.forName("java.lang.String");
    ptypes[1] = Class.forName("java.util.Hashtable");
    Method m = c.getMethod("func", ptypes);
    Test obj = new Test();
    Object arg[] = new Object[2];
    arg[0] = new String("Hello,world");
    arg[1] = null;
    Object r = m.invoke(obj, arg);
    String rval = (String)r;
    System.out.println(rval);
}
    

运行时变更fields内容

与先前两个动作相比, “变更field内容”轻松多了,因为它不需要参数和自变量。首先调用Class的getField()并指定field名称。获得特定的Field object之后便可直接调用Field的get()和set(),

Public class Test{
   public double d;
   public static void main(String args[]){
       Class c = Class.forName("Test");
       Field f = c.getField("d");//指定field名称
       Test obj = new Test();
       System.out.println("d=" + (Double)f.get(obj));
       f.set(obj, 12.34);
       System.out.println("d=" + obj.d);
       }
}

猜你喜欢

转载自blog.csdn.net/weixin_43907332/article/details/86061673