package com.xin.test;
/**
* Created by r.x on 2017/7/6.
*/
public class User {
private String name;
private int age;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", 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;
}
}
待反射的类
package com.xin.test;
/**
* Created by r.x on 2017/7/6.
*/
public class ReflectDemo {
public void outer(User user, String job, int time) {
System.out.println("公众信息:" + user.getName() + "," + user.getAge() + "岁。表面从事" + job + "工作长达" + time + "年");
}
public void inner(User user, String job, int time) {
System.out.println("内部消息:" + user.getName() + "," + user.getAge() + "岁。实际从事" + job + "工作长达" + time + "年");
}
}
单元测试类
package com.xin.test;
import org.junit.Test;
import java.lang.reflect.Method;
/**
* Created by r.x on 2017/7/6.
*/
public class ReflectDemoTest {
@Test
public void testOuter() throws Exception{
Class<?> clazz = ReflectDemo.class;
Object reflectDemo = clazz.newInstance();
// 通过getMethod获取public方法
// **注意:int.class不能写成Integer.class,否则会报NoSuchMethodException**
Method outer = clazz.getMethod("outer", User.class, String.class, int.class);
User user = new User() {
{
setName("老王");
setAge(38);
}
};
outer.invoke(reflectDemo, user, "程序猿", 5);
}
@Test
public void testInner() throws Exception {
Class<?> clazz = Class.forName("com.xin.test.ReflectDemo");
Object reflectDemo = clazz.newInstance();
// 通过getDeclaredMethod获取
Method inner = clazz.getDeclaredMethod("inner", User.class, String.class, int.class);
// 必须设置为true,否则会抛出NoSuchMethodException
inner.setAccessible(true);
User user = new User() {
{
setName("老王");
setAge(38);
}
};
inner.invoke(reflectDemo, user, "单身狗", 25);
}
}