实体类person.java
public class Person {
public String name = "张三";private int age = 23;
public Person() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void eat(){
System.out.println("吃....");
}
public void eat(String name){
System.out.println("吃...."+name);
}
public String sayHello(String name){
return "Hello "+name;
}
}
测试类ReflectDemo.java
public class ReflectDemo {
@Test
// 获得Class对象
public void demo1() throws ClassNotFoundException{
// 类名.class
Class clazz1 = Person.class;
// 实例.getClass()
Class clazz2 = new Person().getClass();
// 通过Class的静态方法的方式:
Class clazz3 = Class.forName("com.itheima.domain.Person");
}
@Test
// 生成类的实例
public void demo2() throws Exception{
// 通过Class的静态方法的方式:
Class clazz = Class.forName("com.itheima.domain.Person");
Person p1 = (Person) clazz.newInstance(); // Person p = new Person();
Constructor c = clazz.getConstructor();
Person p2 = (Person) c.newInstance();
}
@Test
// 获得属性:
public void demo3() throws Exception{
Class clazz = Class.forName("com.itheima.domain.Person");
Field field1 = clazz.getField("name");
Person p = (Person) clazz.newInstance();
System.out.println(field1.get(p));// new Person().name;
Field field2 = clazz.getDeclaredField("age");
field2.setAccessible(true);
System.out.println(field2.get(p));// new Person().age;
}
@Test
// 获得方法:
public void demo4()throws Exception{
Class clazz = Class.forName("com.itheima.domain.Person");
Method method1 = clazz.getMethod("eat",String.class);
Person p = (Person) clazz.newInstance();
method1.invoke(p, "肘子");
Method method2 = clazz.getDeclaredMethod("sayHello", String.class);
method2.setAccessible(true);
String s = (String) method2.invoke(p, "Jack");
System.out.println(s);
}
}