标签:edm types str type close pac color f11 name
一个小小的Demo, 对Class不理解的去看看慕课网的反射
package com.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Test { /** * Class 所有类的类类型 * getMethods 取public方法 * getDeclaredMethods() 取自身的所有方法包括(private 等) * @param args */ public static void main(String[] args) { Class c = Student.class; //构造函数 Constructor [] cons = c.getConstructors(); for (Constructor constructor : cons) { Class[] params = constructor.getParameterTypes(); System.out.print(constructor.getName()+"("); for (int i = 0; i < params.length; i++) { System.out.print(params[i].getName()+","); } System.out.println(")"); } System.out.println("==================================="); //方法 Method[] m = c.getMethods(); for (Method method : m) { Class[] params = method.getParameterTypes(); System.out.print(method.getReturnType().getName() + " " +method.getName()+"("); for (int i = 0; i < params.length; i++) { System.out.print(params[i].getName()+","); } System.out.println(")"); } System.out.println("==================================="); //字段 Field[] f = c.getDeclaredFields(); for (Field field : f) { System.out.println(field.getType().getName() + " " +field.getName()); } try { //单个方法的调用 Student s = new Student(); Method method = c.getMethod("sayHello", new Class[]{}); method.invoke(s); //单个字段的取值 请看下面的Field使用,个人觉得写的不错 } catch (Exception e) { e.printStackTrace(); } } }
package com.reflect; public class Student { private String name; private Integer age; public Student(){} public Student(String name, Integer age){ this.name = name; this.age = age; } public void sayHello(){ System.out.println("hello."); } private void sayGood(){ System.out.println("good."); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
Field 使用: 转载 http://www.cnblogs.com/manuosex/p/3852716.html
标签:edm types str type close pac color f11 name
原文地址:http://www.cnblogs.com/eason-d/p/7779378.html