标签:tde api ref 过程 动态语言 缓存 lin over declared
public class TestReflection {
public static void main(String[] args) throws Exception {
// 通过"类名.class"创建 Class 类(运行时类)的对象
Class<Person> clazz = Person.class;
// 1.创建 clazz 对应的运行时类 Person 的对象并赋给 Person 类对象的引用 p
Person p = clazz.newInstance();
// 2.通过反射,调用运行时类的属性
Field f1 = clazz.getField("age");// 调 public 修饰的属性并赋给 Field 类对象的引用 f1
f1.set(p, 16);
Field f2 = clazz.getDeclaredField("name");// 调非 public 修饰的属性并赋给 Field
// 类对象的引用 f2
f2.setAccessible(true);
f2.set(p, "chen");
System.out.println(p);// Person [age=16, name=chen]
// 3.通过反射,调用运行时类的
Method m1 = clazz.getMethod("custom");
m1.invoke(p);// custom method
Method m2 = clazz.getMethod("custom", String.class);
m2.invoke(p, "arg");// custom method arg
// 说明唯一性
System.out.println(clazz == new Person().getClass());// true
}
}
class Person {
public int age;
private String name;
public Person() {
super();
}
public Person(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}
public void custom() {
System.out.println("custom method");
}
public void custom(String s) {
System.out.println("custom method " + s);
}
}
标签:tde api ref 过程 动态语言 缓存 lin over declared
原文地址:http://www.cnblogs.com/chendifan/p/6569116.html