反射机制获取类方法

ackage Reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class Test1 {
public static void main(String[] args) {
try {
Class clazz = Class.forName(“Reflect.Student”);
// Method[] ms = clazz.getMethods(); //获取到类的所有公有的方法
Method[] ms = clazz.getDeclaredMethods();//获取类所有方法,包含公有和私有
for (Method m : ms){
System.out.println("方法名 "+m.getName());
System.out.println("返回值类型 "+m.getReturnType());
System.out.println("修饰符 "+m.getModifiers());
//获取方法的参数类型,是一个数组,方法有几个参数,数据就有几个元素
Class[] pcs = m.getParameterTypes();
if (pcs !=null && pcs.length > 0){
for (Class p:pcs) {
System.out.println(“参数类型是 “+p.getName());
}
}
System.out.println(”----------------------------------------”);
}

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();

    }
}

}
package Reflect;

public class Student extends Person implements Move,Study{
public Student(){
System.out.println(“无参构造”);
}
public Student(String school){
System.out.println(“public有参构造”);
this.school=school;
}
private Student (String name,int age){
System.out.println(“private 有参构造”);
this.name=name;
this.age=age;
}
String school;
public void showInfo(){
System.out.println("学校是: "+this.school);
}
@Override
public void moveType() {
System.out.println(“学习知识”);
}

@Override
public void studyInfo() {
    System.out.println("开车学习");

}
private void test(String name){

}
public String getSchool(){
    return this.school;
}

}

上一篇:反射机制调用指定属性


下一篇:8 种图数据库对 NULL 属性值支持情况