反射最大的好处是解耦
package cn.hncu.reflect.ex;
public class person {
private String name;
private int age;
public static int count=0;
public person() {
}
public person(String name) {
this.name = name;
}
public person(String name, int age) {
this.name = name;
this.age = age;
}
private person(int age){
this.age = age;
}
private int sum(int n){
int res=0;
for(int i=1;i<=n;i++){
res+=i;
}
return res;
}
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;
}
@Override
public String toString() {
return "name=" + name + ",age=" + age;
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.junit.Test;
//类的解剖(获取类的定义信息)
public class reflectDecompose {
//获取类的方法:找出一个类中定义了些什么方法,这是一个非常有价值也非常基础的反射用法。
@Test
public void fetchMethod() throws Exception{
Class c=Class.forName("cn.hncu.reflect.ex.person");
//获取当前类及其父类的公开方法(私有方法不能访问)--此权限相当于person对象
// Method ms[]=c.getMethods();
//获取当前类所有方法(可以访问私有方法,父类方法不能访问)--此权限相当于暴力访问
Method ms[]=c.getDeclaredMethods();
for(int i=0