我们建立一个Person类,对此进行反射操作。
package myReflection; public class Person { private String name; private String id; Person(){} /** * @param name * @param id */ public Person(String name, String id) { super(); this.name = name; this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } }
分别对constructor‘、属性和方法反射
test1====无参数构造函数
test2 ====有参数构造函数
test3=====属性
test4=====方法
package myReflection; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.junit.Test; public class useReflection { public static void main(String[] args) throws ClassNotFoundException { // TODO Auto-generated method stub Class c1=Person.class; Class c2=new Person().getClass(); Class c3=Class.forName("myReflection.Person"); } @Test public void test4() throws Exception{ Class c=Class.forName("myReflection.Person"); Person p=(Person) c.newInstance(); Method m=c.getDeclaredMethod("setName", String.class); m.invoke(p, "Lannister"); System.out.println(p.getName()); } @Test public void test3() throws Exception{ try { Class c=Class.forName("myReflection.Person"); Person p=(Person) c.newInstance(); Field f1=c.getDeclaredField("name"); f1.setAccessible(true); f1.set(p, "Stark"); System.out.println(f1.get(p)); } catch (Exception e) { // TODO: handle exception } } @Test public void test2() throws Exception { Class c=Class.forName("myReflection.Person"); Constructor cs=c.getConstructor(String.class,String.class); Person p1=(Person)cs.newInstance("Jon","Snow"); System.out.println(p1.getId()+" "+p1.getName()); } @Test public void test1() throws Exception{ Class cl3=Class.forName("myReflection.Person"); Person p =(Person)cl3.newInstance(); p.setName("Tully"); System.out.println(p.getName()); } }
时间: 2024-10-09 20:30:43