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

原创 2016年08月28日 21:06:17
下面是我写的一个利用反射来调用类的所有信息的例子。包括再运行这个程序的时候遇到的问题,和请教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 我发的帖子和回答如下:


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 in public 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  

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 )

$ ls
ClassViewer.java
$ javac ClassViewer.java
$ java ClassViewer ClassViewer
package 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):

shareedit

版权声明:本文为博主原创文章,若要转载请注明出处!^_^

利用Java反射机制输出类的信息

利用Java的反射机制可以对Java类进行解析。本程序以类名为输出参数,输出该类的名称、继承的父类、实现的接口、包含的域、拥有的构造器以及方法,以及该类的继承链。 代码如下: package ...

Java基础-利用反射获取类信息

反射机制 反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语...

php 利用反射API获取类信息

PHP具有完整的反射API,可以对类、接口、函数、方法和扩展进行反向工程。反射API并提供方法取出函数、类和方法中的文档注释。本文将介绍使用PHP反射API获取类信息的方法,提供完整演示代码。...
  • fdipzone
  • fdipzone
  • 2017年05月24日 22:09
  • 23946

java利用反射获取类信息

在java.lang.reflect包中有三个类Field、Monthod和Constructor分别描述类的域、方法和构造器。还可以使用java.lang.reflect包中的Modifier类的静...

从配置文件读取数据连接信息,利用泛型和java反射机制,写一个公共的增删改查数据库操作类

背景: 最近在学习java,然后就看了spring jdbc。对于菜鸟来说,看得实在头大,然而还有强迫症作祟最是要不得。又要导入common的相关jar包,又要导入mysql的jar包,还要导入spr...

ORM尝试二 利用反射获取类信息

一 思路:可以根据 仅仅是类名 类的实例 获取类的信息而我们需要获取到的信息有: 类名 成员变量的名称 成员变量的类型 成员变量的 getter 和 setter 成员变量的 value 二 解决方法...

MFC 利用控制台输出调试信息

  • 2012年07月12日 09:46
  • 755B
  • 下载

Android利用反射获取WLAN热点信息

private static final String TAG = "wifiHelper"; private WifiManager mWifiManager = null;public boole...

java使用poi导出excel的内容,同时可以利用反射进行动态获取信息

Java-poi 实现excel的导出,并且可以作为我们的工具类来使用

java中利用反射获得对象的各种信息

package com.dao; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.Pr...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:利用反射,输出类的所有信息
举报原因:
原因补充:

(最多只允许输入30个字)