写个父类:
package reflectgetclass;
public class Person {
String name;
public Person(){}
public Person(String name){
this.name= name;
}
}
写个子类:
package reflectgetclass;
public class Student extends Person implements Runnable,Comparable {
private int classId ;
private String name;
private double score;
public Student(){}
public Student(int classId){
this.classId = classId;
}
public Student(String name,double score){
this.name = name;
this.score = score;
}
public void m1(){
System.out.println("this is the first method");
}
public void m1(String s,double d){
System.out.println(s+"学生的成绩是"+d);
}
public int m2(){
return this.classId;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
利用反射获得该子类中的属性,方法,构造,父类及接口:
package reflectgetclass;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* 通过反射获得类的内容(属性、方法、构造、父类、实现的接口)
* @author 流马
*
*/
public class ReflectGetClass {
public static void main(String[] args) throws Exception {
Class c = Class.forName("reflectgetclass.Student");//得到类
StringBuffer sb = new StringBuffer();//常见可变长存储的StringBuffer sb
sb.append(Modifier.toString(c.getModifiers())+" class ");
sb.append(c.getName()+"{\n");
//得到属性内容
Field[] fields = c.getDeclaredFields();
for(Field f : fields){
sb.append("\t"+Modifier.toString(f.getModifiers())+" "+f.getType().getName()+" "+f.getName()+"\n");
}
//得到构造
Constructor[] cs = c.getDeclaredConstructors();
for(Constructor con : cs){
sb.append("\t"+Modifier.toString(con.getModifiers())+" "+c.getName()+"(");
//得到构造中的参数列表
Class[] classes = con.getParameterTypes();
for(Class cla: classes){
if(cla!=classes[classes.length-1]){
sb.append(cla.getName()+",");
}else{
sb.append(cla.getName());
}
}
sb.append("){}");
sb.append("\n");
}
//得到方法
Method[] methods = c.getDeclaredMethods();
for(Method me: methods){
sb.append(Modifier.toString(me.getModifiers())+" "+me.getReturnType().getName()+" "+me.getName()+"(");
//得到方法的参数类型
Class[] css = me.getParameterTypes();
for(Class ca : css){
if(ca!=css[css.length-1]){
sb.append(ca.getName()+",");
}else{
sb.append(ca.getName());
}
}
sb.append("){}");
sb.append("\n");
}
sb.append("}");
//得到父类
Class parentClass = c.getSuperclass();
//得到实现的接口
Class[] interfaces = c.getInterfaces();
for(Class it : interfaces){
sb.append("\n"+it.getName()+"\n");
}
System.out.println(sb);//打印出SringBuffer里面的内容
}
}
运行结果: