1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| package com.redisc;
import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
class Person { public String getName() { return name; }
public String getName2() { return name2; }
public void setName(String name) { this.name = name; }
public String name; private String name2;
public Person(String name) { this.name = name; }
public Person() { } }
public class Test {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class person = Class.forName("com.redisc.Person");
// 构造一个对象 Person person1 = (Person) person.getDeclaredConstructor().newInstance(); System.out.println(person1);
// 通过构造器创建对象 Person person2 = (Person) person.getDeclaredConstructor(String.class).newInstance("123"); System.out.println(person2.getName());
// 通过反射调用普通方法 Method setName = person.getDeclaredMethod("setName", String.class); setName.invoke(person2, "333"); System.out.println(person2.getName());
// 通过反射操作属性 Field name = person.getDeclaredField("name"); name.set(person2, "555"); System.out.println(person2.getName());
// 通过反射操作私有属性 Field name2 = person.getDeclaredField("name2"); name2.setAccessible(true); name2.set(person2,"777"); System.out.println(person2.getName2()); } }
|