zoukankan      html  css  js  c++  java
  • Reflection反射机制

    import com.sun.jdi.InvocationException;

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

    public class TestReflection {
    public TestReflection(){
    type = 1;
    }
    public TestReflection(Integer t){
    type = t;
    }
    private Integer type;

    public Integer plus(Integer num1,Integer num2) {
    return num1 + num2;
    }

    public Integer minus(Integer num1,Integer num2) {
    return num1 - num2;
    }

    public static void main(String[] args) throws ClassNotFoundException,NoSuchMethodException,InstantiationException,IllegalAccessException, InvocationTargetException {
    //根据类全限定名称获取class类型
    Class myTest = Class.forName("TestReflection");
    System.out.println(myTest.getName());
    //遍历构造函数
    Constructor[] constructors = myTest.getConstructors();
    for(Constructor con : constructors){
    System.out.println(con.toString());
    }
    //遍历所有方法
    Method[] methods = myTest.getDeclaredMethods();
    for(Method method:methods){
    System.out.println(method.toString());
    }
    //遍历所有字段
    Field[] fields = myTest.getDeclaredFields();
    for(Field field : fields){
    System.out.println("字段:"+field.getName());
    }
    //实例化对象,执行方法
    Object obj = myTest.getConstructor().newInstance();
    Method plus1 = myTest.getDeclaredMethod("plus", Integer.class, Integer.class);
    Method minus1 = myTest.getDeclaredMethod("minus", Integer.class, Integer.class);
    Object plusResult = plus1.invoke(obj,5,3);
    System.out.println(plusResult);

    Object minsResult = minus1.invoke(obj,6,2);
    System.out.println(minsResult);

    }

    }


  • 相关阅读:
    FCKEditor配置
    在线文档编辑器原理
    DVD格式(vob)文件转换avi,转换后可嵌入HTML中播放
    Javascript小技巧
    sql server 查询当前记录的前一条和后一条记录
    [翻译]开发一个自己的HTML在线编辑器(二)
    在线编辑器(4)TAB键缩进功能
    IIS不能浏览ASP页面
    C#枚举类型的使用《转》
    C#中泛型使用《转》
  • 原文地址:https://www.cnblogs.com/TestMa/p/10636559.html
Copyright © 2011-2022 走看看