利用反射,输出类的所有信息

来源:互联网 发布:网络银行的特点有 编辑:程序博客网 时间:2024/05/16 07:53
下面是我写的一个利用反射来调用类的所有信息的例子。包括再运行这个程序的时候遇到的问题,和请教stack overflow 之后得到的一些回答,希望可以和大家一起分享一下经验。
package reflect;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Modifier;public class ClassViewer {    public static void view(String clazName) throws ClassNotFoundException{        Class clz=Class.forName(clazName);        Package p=clz.getPackage();        System.out.printf("package %s;%n", clz.getName());        int modifier=clz.getModifiers();//取得类型的修饰常数        System.out.printf("%s %s %s {%n",                 Modifier.toString(modifier),                Modifier.isInterface(modifier) ? "interface" :"class",                clz.getName()                );        //取得声明的数据成员代表对象        Field[] fields =clz.getDeclaredFields();        for(Field field:fields){            //显示权限修饰            System.out.printf("\t%s %s %s;%n",                     Modifier.toString(field.getModifiers()),                    field.getType().getName(),                    field.getName()                    );        }        //取得声明的创建方法代表对象        Constructor[] constructors=clz.getDeclaredConstructors();        for(Constructor constructor:constructors){            System.out.printf("\t%s %s();%n",                     Modifier.toString(constructor.getModifiers()),                    constructor.getName()                    );        }        //取得声明的方法成员代表对象        Method[] methods=clz.getDeclaredMethods();        for(Method method:methods){            System.out.printf("\t%s %s %s;%n",                     Modifier.toString(method.getModifiers()),                    method.getReturnType(),                    method.getName()                    );        }        System.out.println("}");    }public static void main(String[] args) {        try {            ClassViewer.view("java.lang.reflect.Constructor");        }catch(ArrayIndexOutOfBoundsException e){            System.out.println("Array Index Out Of Bounds Exception ");        }        catch (ClassNotFoundException e) {            System.out.println("can not find the class");        }    }}
运行结果如下:
package java.lang.reflect.Constructor;public final class java.lang.reflect.Constructor {private java.lang.Class clazz;private int slot;private [Ljava.lang.Class; parameterTypes;private [Ljava.lang.Class; exceptionTypes;private int modifiers;private transient java.lang.String signature;private transient sun.reflect.generics.repository.ConstructorRepository genericInfo;private [B annotations;private [B parameterAnnotations;private volatile sun.reflect.ConstructorAccessor constructorAccessor;private java.lang.reflect.Constructor root; java.lang.reflect.Constructor();public boolean equals;public class java.lang.String toString;public int hashCode;public int getModifiers;public class java.lang.String getName;public interface java.lang.annotation.Annotation getAnnotation;public class [Ljava.lang.annotation.Annotation; getDeclaredAnnotations;public class java.lang.Class getDeclaringClass;private interface sun.reflect.generics.factory.GenericsFactory getFactory; class sun.reflect.generics.repository.ConstructorRepository getGenericInfo;public class [Ljava.lang.Class; getParameterTypes; class [B getRawAnnotations;public class [Ljava.lang.reflect.TypeVariable; getTypeParameters;public boolean isSynthetic;public transient class java.lang.Object newInstance;public class java.lang.String toGenericString; class java.lang.reflect.Constructor copy;public class [Ljava.lang.reflect.Type; getGenericParameterTypes;public class [[Ljava.lang.annotation.Annotation; getParameterAnnotations;public int getParameterCount;public boolean isVarArgs;public interface java.lang.reflect.AnnotatedType getAnnotatedReturnType; class [B getAnnotationBytes;public class [Ljava.lang.Class; getExceptionTypes;public class [Ljava.lang.reflect.Type; getGenericExceptionTypes; void handleParameterNumberMismatch; boolean hasGenericInformation; void specificToGenericStringHeader; void specificToStringHeader;public interface java.lang.reflect.AnnotatedType getAnnotatedReceiverType;private interface sun.reflect.ConstructorAccessor acquireConstructorAccessor; interface sun.reflect.ConstructorAccessor getConstructorAccessor; class [B getRawParameterAnnotations; class java.lang.String getSignature; int getSlot; void setConstructorAccessor;}

在次过程中遇到的问题和在stack overflow 我发的帖子和回答如下:


0down vote favorite
2

The console shows a ArrayIndexOutOfBoundsException when I run this program, it could not find the argument inmain(). I really don't know the reason, because I do have the argumentString[] args inpublic static void main(String[] args):

package reflect;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Modifier;import java.time.chrono.JapaneseChronology;public class ClassViewer {    public static void view(String clazName) throws ClassNotFoundException{        Class clz=Class.forName(clazName);        Package p=clz.getPackage();        System.out.printf("package %s;%n", clz.getName());        int modifier=clz.getModifiers();//取得类型的修饰常数        System.out.printf("%s %s %s {%n",                 Modifier.toString(modifier),                Modifier.isInterface(modifier) ? "interface" :"class",                clz.getName()                );        //取得声明的数据成员代表对象        Field[] fields =clz.getDeclaredFields();        for(Field field:fields){            //显示权限修饰            System.out.printf("\t%s %s %s;%n",                     Modifier.toString(field.getModifiers()),                    field.getType().getName(),                    field.getName()                    );        }        //取得声明的创建方法代表对象        Constructor[] constructors=clz.getDeclaredConstructors();        for(Constructor constructor:constructors){            System.out.printf("\t%s %s();%n",                     Modifier.toString(constructor.getModifiers()),                    constructor.getName()                    );        }        //取得声明的方法成员代表对象        Method[] methods=clz.getDeclaredMethods();        for(Method method:methods){            System.out.printf("\t%s %s %s;%n",                     Modifier.toString(method.getModifiers()),                    method.getReturnType(),                    method.getName()                    );        }        System.out.println("}");    }public static void main(String[] args) {        try {            ClassViewer.view(args[0]);        }catch(ArrayIndexOutOfBoundsException e){            System.out.println("Array Index Out Of Bounds Exception ");        }        catch (ClassNotFoundException e) {            System.out.println("can not find the class");        }    }}
shareeditdeleteflag
 
2 
When you are running the code after compiling it, You have to pass argument which is calledcommand line argument. Suppose you want to pass a String Checking in your code then you have to run file asjava ClassViewer Checking. – Sanket Makani8 hours ago
 
Did you pass a argument to the program? – tkausl8 hours ago
 
Make sure you pass arguments toview. For testing you could change ` ClassViewer.view(args[0]);` to pass an argument like ` ClassViewer.view(className);` where className is a name of a class. – c0der6 hours ago
 
Please translate the comments to English as well. As it is, they are useless for most readers who might want to help you. – Rad Lexus 3 hours ago
 
c0der is right , i was so careless to ignore that the arguement of the static method view(String className). so when i wanna run the method view . i should pass an argument of String and it means a name of a class. so if i pass a correct meaning name like"java.lang.reflect.Constructor" as the argument of the view , it would be ok .change"ClassViewer.view(args[0]);"like below "ClassViewer.view("java.lang.reflect.Constructor");" it would be ok – qiaopan Ma 1 min ago   edit  
  

1 Answer

activeoldestvotes
up vote0down vote accept

As has been noted in the comments appropriately, you must provide command-line arguments.

Here is example of that on Linux terminal (Mac also has terminal, and for Windows users there's powershell or CMD )

$ lsClassViewer.java$ javac ClassViewer.java$ java ClassViewer ClassViewerpackage ClassViewer;public class ClassViewer {    public ClassViewer();    public static void view;    public static void main;}

Note that apparently class has to be in the same directory

$ java ClassViewer /home/xieerqi/bin/java2/soundexClass                        can not find the class$ # This didn't work, so copy the soudnexClass.class into current directory$ cp /home/xieerqi/bin/java2/soundexClass.class  .$ java ClassViewer soundexClass                                                package soundexClass;public class soundexClass {    public soundexClass();    public static void getSoundex;    public static void main;}

This also can be done with IDEs (note , that each IDE has their own way):

  • Netbeans
  • Eclipse
  • jGRASP
shareedit

0 0