java反射(reflex)

三种方式

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))