利用java反射机制打印类的信息

来源:互联网 发布:淘宝提升关键词排名 编辑:程序博客网 时间:2024/05/18 00:31

利用java的反射机制获取类的信息

包括类成员函数的信息,类属性的信息和类构造函数的信息

package reflect;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Main {public static void main(String[] args) throws NoSuchMethodException, SecurityException {// TODO Auto-generated method stubInteger a  = 10;System.out.println("类成员函数的信息");getMessageForMethods(a);System.out.println("==============================================");System.out.println("类成员变量的信息");getMessageForField(a);System.out.println("==============================================");System.out.println("类构造函数的信息");getMessageForConstructor(a);}/* * 打印类的成员函数的信息,包括方法名,方法返回值,方法参数类型 */public static void getMessageForMethods(Object obj){//要获取类的信息,先获取类的类类型Class c = obj.getClass();//获取类的名字System.out.println("类的名字是" + c.getName());//获取类的所有public的方法 包括从父类继承的Method[] ms = c.getMethods();//打印出方法名 返回值 参数for(Method m : ms){//得到返回类型的类类型Class returnType = m.getReturnType();//打印返回值System.out.print("返回类型是" + returnType.getName());System.out.println( "函数名是" + m.getName());//得到方法参数的类类型Class[] paramType = m.getParameterTypes();//打印参数类型for(Class p : paramType)System.out.println(p.getName() + " ");}}/* * 打印类的属性信息 */public static void getMessageForField(Object obj){Class c = obj.getClass();//成员变量也是对象//java.lang.reflect.field中封装了对成员变量的操作Field[] f = c.getFields();//打印成员变量for(Field field : f){//获得成员变量类型的类类型Class c1 = field.getType();System.out.print(c1.getName() + "  ");System.out.println(field.getName());}}/* * 打印构造函数的信息 */public static void getMessageForConstructor(Object obj) throws NoSuchMethodException, SecurityException{Class c = obj.getClass();//构造函数也是对象//java.lang.Constructor中封装了构造函数的信息Constructor[] con = c.getDeclaredConstructors();for (Constructor constructor : con){System.out.print(constructor.getName() + "(");//获取构造函数的参数Class[] param = constructor.getParameterTypes();for(Class class1 : param){System.out.print(class1.getName() + "  ");}System.out.println(")");}}}

0 0
原创粉丝点击