美文网首页
java反射(reflex)

java反射(reflex)

作者: 沉思的老猫 | 来源:发表于2017-12-09 15:58 被阅读0次

    三种方式

    Class c1 = Class.forName("com.zheng.reflex.ReflexExample");
    Class c2 = ReflexExample.class;
    Class c3 = new ReflexExample().getClass();
    

    获取属性值

    ReflexExample reflexExample = new ReflexExample(1,"张三");
    Class c = reflexExample.getClass();
    Field[] declaredFields = c.getDeclaredFields();
    for (int i = 0; i < declaredFields.length; i++) {
         Field df = declaredFields[i];
         Object value = df.get(reflexExample);
         String fieldName = df.getName();
         String fieldValue = String.valueOf(value);
         Boolean isInstanceOf = value instanceof Integer;
         System.out.println("name:"+fieldName+" value:"+fieldValue+" 类型:"+ yes);
    }
    

    获取构造的get方法

    Method[] Methods = c.getDeclaredMethods();
    for(Method method : Methods){
      if(method.getModifiers() == 1 && !method.isVarArgs() && !"void".equals(method.getReturnType().getName())){
         System.out.println("method:"+method.getName());
       }
    }
    

    相关文章

      网友评论

          本文标题:java反射(reflex)

          本文链接:https://www.haomeiwen.com/subject/lccjixtx.html