您的位置:首页 > 其它

类反射基本用法

2016-10-20 07:33 281 查看
//这是用来测试的person类

package cn.hncu.reflect;
public class Person {
public String name;
public int age;
public Person() {}
public Person(String name, int age) {
this.name = name;
this.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;
}
private int sum(){
return 0;
}
}


package cn.hncu.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ReflectDemo {
private static final String CLASS_NAME="cn.hncu.reflect.Person";
public static void main(String[] args) {
try {
//getMethods();
// getConstructors();
getFiled();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void getFiled() throws Exception {
Class c=Class.forName(CLASS_NAME);
Field fld[]=c.getFields();//c.getDeclaredFields()
for(int i=0;i<fld.length;i++){
System.out.println(fld[i].getName());
System.out.println(fld[i].getModifiers());
System.out.println(fld[i].getDeclaringClass());
System.out.println(fld[i].getType());
}
}
private static void getConstructors() throws Exception {
Class c=Class.forName(CLASS_NAME);
//注意:子类不能继承父类的构造方法,所以不论是getConstructors还是getDeclaredConstructors都只能获取到子类的。
Constructor<Person> cons[]=c.getConstructors();
for(int i=0;i<cons.length;i++){
//修饰符
System.out.println(Modifier.toString(cons[i].getModifiers()));
//方法名
System.out.println(cons[i].getName());
//方法所在的类
System.out.println(cons[i].getDeclaringClass());
//方法参数
Class params[]=cons[i].getParameterTypes();
for(int j=0;j<params.length;j++){
System.out.println(params[j]);
}
//异常
Class excepType[]=cons[i].getExceptionTypes();
for(int j=0;j<excepType.length;j++){
System.out.println(excepType[j].getName());
}
System.out.println("---------一个构造方法-----------");
}

}
private static void getMethods() throws Exception {
Class c=Class.forName(CLASS_NAME);
//Method m[]=c.getMethods();获取子类和父类中public方法
Method m[]=c.getDeclaredMethods();//获取该类中所有的方法,包括私有
for(int i=0;i<m.length;i++){
//修饰符
System.out.println(Modifier.toString(m[i].getModifiers()));
//方法名
System.out.println(m[i].getName());
//方法所在的类
System.out.println(m[i].getDeclaringClass());
//方法参数
Class params[]=m[i].getParameterTypes();
for(int j=0;j<params.length;j++){
System.out.println(params[j]);
}
//方法返回类型
Class returnType=m[i].getReturnType();
System.out.println(returnType);

//异常
Class excepType[]=m[i].getExceptionTypes();
for(int j=0;j<excepType.length;j++){
System.out.println(excepType[j].getName());
}
System.out.println("---------一个方法-----------");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: