版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kangaroo_07/article/details/78058070
package com.reflect;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 反射对属性、方法的操作
* @author lr
*
*/
public class Demo4 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
Test test =new Test();
Class<?> clazz =test.getClass();
Object obj =clazz.newInstance();
//获得fun方法 方式一:
Method method = clazz.getMethod("fun", String.class,int.class);
//获得fun方法 方式二:
Method method2 = clazz.getMethod("fun", new Class[]{String.class,int.class});
//方法调用 方式一:
method.invoke(obj, "lr",25);
//方法调用 方式二:
method2.invoke(obj, new Object[]{"lr",25});
//获取属性name
Field fieldName = clazz.getDeclaredField("name");
Field fieldAge = clazz.getDeclaredField("age");
//私有属性设置其可获得
fieldName.setAccessible(true);
fieldAge.setAccessible(true);
//为属性赋值
fieldName.set(obj, "tom");
fieldAge.set(obj, 25);
//打印属性值
System.out.println(fieldName.get(obj));
System.out.println(fieldAge.get(obj));
}
}
class Test{
private String name;
private int age;
public void fun(String name,int age){
System.out.println(name+","+age);
}
public Test() {
super();
}
public Test(String name, int age) {
super();
this.name = name;
this.age = age;
}
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;
}
}
打印输出:
lr,25
lr,25
tom
25