Java中的反思 - 意外输出

时间:2012-11-19 05:25:48

标签: java reflection

我正在编写一个类来获取有关使用反射的指定类的信息。输出包括完全限定的方法名称,我不希望输出中的完全限定名称。

这是一个例子。而不是:

public static java.lang.String java.lang.Integer.toString(int,int)

我希望它显示:

public static String toString(int, int);

以下是我班级的简化版本:

public class jr
{
    public static void main(String[] args) throws ClassNotFoundException
    {
        jr j = new jr();

        String str = java.lang.Integer;

        Class cls = Class.forName(str);
        j.print(cls);   
    }

   /*
    * Displays the Methods of the given class. The items displayed depends on 
    * the options entered.
    *
    * @param    cl    The class to be displayed
    */ 
    public void methods(Class cl)
    {
        // Get the Methods of the Class cl
        Method[] me = cl.getDeclaredMethods();

        for(Method x : me)
        {            
            System.out.println(x);
        }
    }

   /*
    * Displays the information about the class. Uses the options to filter which
    * information is printed.
    *
    * @param    cl    The class to be displayed
    */         
    public void print(Class cl)
    {
        System.out.println("\nMETHODS:");
        methods(cl);
    }
}

我总是可以解析String来清理它,但这看起来有点像黑客。我认为没有更好的办法。

4 个答案:

答案 0 :(得分:1)

尝试以下方法:

System.out.println(x.toString().replaceAll("([\\w_$]+\\.)+", ""));

答案 1 :(得分:1)

所以,我基本上从toString偷走了method方法并进行了一些小调整......

它现在转储public static String toString(int,int)

之类的输出
public class TestReflection {

    public static void main(String[] args) throws ClassNotFoundException {
        TestReflection tr = new TestReflection();
        String str = "java.lang.Integer";
        Class cls = Class.forName(str);
        tr.print(cls);
    }

    /*
     * Displays the Methods of the given class. The items displayed depends on
     * the options entered.
     *
     * @param    cl    The class to be displayed
     */
    public void methods(Class cl) {
        // Get the Methods of the Class cl
        Method[] me = cl.getDeclaredMethods();

        for (Method x : me) {
            System.out.println(toString(x));
        }
    }

    /*
     * Displays the information about the class. Uses the options to filter which
     * information is printed.
     *
     * @param    cl    The class to be displayed
     */
    public void print(Class cl) {
        System.out.println("\nMETHODS:");
        methods(cl);
    }

    public static String getTypeName(Class<?> type) {
        if (type.isArray()) {
            try {
                Class<?> cl = type;
                int dimensions = 0;
                while (cl.isArray()) {
                    dimensions++;
                    cl = cl.getComponentType();
                }
                StringBuffer sb = new StringBuffer();
                sb.append(cl.getName());
                for (int i = 0; i < dimensions; i++) {
                    sb.append("[]");
                }
                return sb.toString();
            } catch (Throwable e) { /*FALLTHRU*/ }
        }
        return type.getName();
    }

    private String toString(Method method) {
        try {
            StringBuilder sb = new StringBuilder();
            int mod = method.getModifiers() & Modifier.methodModifiers();
            if (mod != 0) {
                sb.append(Modifier.toString(mod)).append(' ');
            }
            sb.append(method.getReturnType().getSimpleName()).append(' ');
            sb.append(method.getName()).append('(');
            Class<?>[] params = method.getParameterTypes();
            for (int j = 0; j < params.length; j++) {
                sb.append(getTypeName(params[j]));
                if (j < (params.length - 1)) {
                    sb.append(',');
                }
            }
            sb.append(')');
            Class<?>[] exceptions = method.getExceptionTypes();
            if (exceptions.length > 0) {
                sb.append(" throws ");
                for (int k = 0; k < exceptions.length; k++) {
                    sb.append(exceptions[k].getName());
                    if (k < (exceptions.length - 1)) {
                        sb.append(',');
                    }
                }
            }
            return sb.toString();
        } catch (Exception e) {
            return "<" + e + ">";
        }
    }
}

答案 2 :(得分:1)

我建议你修改方法如下:

public void methods(Class cl) {
    // Get the Methods of the Class cl
    Method[] me = cl.getDeclaredMethods();

    for (Method x : me) {
        String parameterType = "";
        System.out.println(x);
        Class[] parameterTypes = x.getParameterTypes();
        for (Class c : parameterTypes)
        parameterType = parameterType + c.getSimpleName() + " ,";

        System.out.println(x.getModifiers() + " " + x.getReturnType().getSimpleName() + " " + x.getName() + " ( "
            + parameterType + " )");
    }
    }

<强>输出 方法:

public int java.lang.Integer.hashCode()
1 int hashCode (  )
public boolean java.lang.Integer.equals(java.lang.Object)
1 boolean equals ( Object , )
public static java.lang.String java.lang.Integer.toString(int)
9 String toString ( int , )
public static java.lang.String java.lang.Integer.toString(int,int)
9 String toString ( int ,int , )
public java.lang.String java.lang.Integer.toString()
1 String toString (  )
public static java.lang.String java.lang.Integer.toHexString(int)
9 String toHexString ( int , )
public static int java.lang.Integer.compare(int,int)
9 int compare ( int ,int , )
public int java.lang.Integer.compareTo(java.lang.Object)
4161 int compareTo ( Object , )
public int java.lang.Integer.compareTo(java.lang.Integer)
1 int compareTo ( Integer , )
public static java.lang.Integer java.lang.Integer.decode(java.lang.String) throws java.lang.NumberFormatException
9 Integer decode ( String , )
static void java.lang.Integer.getChars(int,int,char[])
8 void getChars ( int ,int ,char[] , )
public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String,int) throws java.lang.NumberFormatException
9 Integer valueOf ( String ,int , )
public static java.lang.Integer java.lang.Integer.valueOf(int)
9 Integer valueOf ( int , )
public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String) throws java.lang.NumberFormatException
9 Integer valueOf ( String , )
public int java.lang.Integer.intValue()
1 int intValue (  )
public static int java.lang.Integer.reverse(int)
9 int reverse ( int , )
static int java.lang.Integer.stringSize(int)
8 int stringSize ( int , )
public static int java.lang.Integer.reverseBytes(int)
9 int reverseBytes ( int , )
public byte java.lang.Integer.byteValue()
1 byte byteValue (  )
public double java.lang.Integer.doubleValue()
1 double doubleValue (  )
public float java.lang.Integer.floatValue()
1 float floatValue (  )
public long java.lang.Integer.longValue()
1 long longValue (  )
public short java.lang.Integer.shortValue()
1 short shortValue (  )
public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException
9 int parseInt ( String , )
public static int java.lang.Integer.parseInt(java.lang.String,int) throws java.lang.NumberFormatException
9 int parseInt ( String ,int , )
public static int java.lang.Integer.bitCount(int)
9 int bitCount ( int , )
public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,java.lang.Integer)
9 Integer getInteger ( String ,Integer , )
public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,int)
9 Integer getInteger ( String ,int , )
public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String)
9 Integer getInteger ( String , )
public static int java.lang.Integer.highestOneBit(int)
9 int highestOneBit ( int , )
public static int java.lang.Integer.lowestOneBit(int)
9 int lowestOneBit ( int , )
public static int java.lang.Integer.numberOfLeadingZeros(int)
9 int numberOfLeadingZeros ( int , )
public static int java.lang.Integer.numberOfTrailingZeros(int)
9 int numberOfTrailingZeros ( int , )
public static int java.lang.Integer.rotateLeft(int,int)
9 int rotateLeft ( int ,int , )
public static int java.lang.Integer.rotateRight(int,int)
9 int rotateRight ( int ,int , )
public static int java.lang.Integer.signum(int)
9 int signum ( int , )
public static java.lang.String java.lang.Integer.toBinaryString(int)
9 String toBinaryString ( int , )
public static java.lang.String java.lang.Integer.toOctalString(int)
9 String toOctalString ( int , )
private static java.lang.String java.lang.Integer.toUnsignedString(int,int)
10 String toUnsignedString ( int ,int , )

我修改了in-build toGenericString()以满足您的需求:

package SO;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;

public class jr {
    // Modifiers that can be applied to a method in source code
    private static final int LANGUAGE_MODIFIERS = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE
        | Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED | Modifier.NATIVE;

    public static void main(String[] args) throws ClassNotFoundException {
    jr j = new jr();

    String str = "java.lang.Integer";

    Class<?> cls = Class.forName(str);
    j.print(cls);
    }

    /*
     * Displays the Methods of the given class. The items displayed depends on
     * the options entered.
     * 
     * @param cl The class to be displayed
     */
    public void methods(Class cl) {
    // Get the Methods of the Class cl
    Method[] me = cl.getDeclaredMethods();

    for (Method x : me) {
        String parameterType = "";
        System.out.println("simple   :" + x);
        System.out.println("generic  :" + x.toGenericString());
        System.out.println("modified :" + modifiedToGenericString(x));
        ;

    }
    }

    public String modifiedToGenericString(Method m) {
    try {
        StringBuilder sb = new StringBuilder();
        int mod = m.getModifiers() & LANGUAGE_MODIFIERS;
        if (mod != 0) {
        sb.append(Modifier.toString(mod) + " ");
        }
        Type[] typeparms = m.getTypeParameters();
        if (typeparms.length > 0) {
        boolean first = true;
        sb.append("<");
        for (Type typeparm : typeparms) {
            if (!first)
            sb.append(",");
            if (typeparm instanceof Class)
            sb.append(((Class) typeparm).getSimpleName());
            else
            sb.append(typeparm.toString());
            first = false;
        }
        sb.append("> ");
        }

        Type genRetType = m.getGenericReturnType();
        sb.append(((genRetType instanceof Class) ? ((Class) genRetType).getSimpleName() : genRetType.toString())
            + " ");

        // sb.append((m.getDeclaringClass()) + ".");
        sb.append(m.getName() + "(");
        Type[] params = m.getGenericParameterTypes();
        for (int j = 0; j < params.length; j++) {
        sb.append((params[j] instanceof Class) ? ((Class) params[j]) : (params[j].toString()));
        if (j < (params.length - 1))
            sb.append(",");
        }
        sb.append(")");
        Type[] exceptions = m.getGenericExceptionTypes();
        if (exceptions.length > 0) {
        sb.append(" throws ");
        for (int k = 0; k < exceptions.length; k++) {
            sb.append((exceptions[k] instanceof Class) ? ((Class) exceptions[k]).getSimpleName()
                : exceptions[k].toString());
            if (k < (exceptions.length - 1))
            sb.append(",");
        }
        }
        return sb.toString();
    } catch (Exception e) {
        return "<" + e + ">";
    }
    }

    /*
     * Displays the information about the class. Uses the options to filter
     * which information is printed.
     * 
     * @param cl The class to be displayed
     */
    public void print(Class cl) {
    System.out.println("\nMETHODS:");
    methods(cl);
    }
}

使用以下输出:

METHODS:
simple   :public int java.lang.Integer.hashCode()
generic  :public int java.lang.Integer.hashCode()
modified :public int hashCode()
simple   :public boolean java.lang.Integer.equals(java.lang.Object)
generic  :public boolean java.lang.Integer.equals(java.lang.Object)
modified :public boolean equals(class java.lang.Object)
simple   :public static java.lang.String java.lang.Integer.toString(int)
generic  :public static java.lang.String java.lang.Integer.toString(int)
modified :public static String toString(int)
simple   :public static java.lang.String java.lang.Integer.toString(int,int)
generic  :public static java.lang.String java.lang.Integer.toString(int,int)
modified :public static String toString(int,int)
simple   :public java.lang.String java.lang.Integer.toString()
generic  :public java.lang.String java.lang.Integer.toString()
modified :public String toString()
simple   :public static java.lang.String java.lang.Integer.toHexString(int)
generic  :public static java.lang.String java.lang.Integer.toHexString(int)
modified :public static String toHexString(int)
simple   :public static int java.lang.Integer.compare(int,int)
generic  :public static int java.lang.Integer.compare(int,int)
modified :public static int compare(int,int)
simple   :public int java.lang.Integer.compareTo(java.lang.Object)
generic  :public int java.lang.Integer.compareTo(java.lang.Object)
modified :public int compareTo(class java.lang.Object)
simple   :public int java.lang.Integer.compareTo(java.lang.Integer)
generic  :public int java.lang.Integer.compareTo(java.lang.Integer)
modified :public int compareTo(class java.lang.Integer)
simple   :public static java.lang.Integer java.lang.Integer.decode(java.lang.String) throws java.lang.NumberFormatException
generic  :public static java.lang.Integer java.lang.Integer.decode(java.lang.String) throws java.lang.NumberFormatException
modified :public static Integer decode(class java.lang.String) throws NumberFormatException
simple   :static void java.lang.Integer.getChars(int,int,char[])
generic  :static void java.lang.Integer.getChars(int,int,char[])
modified :static void getChars(int,int,class [C)
simple   :public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String,int) throws java.lang.NumberFormatException
generic  :public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String,int) throws java.lang.NumberFormatException
modified :public static Integer valueOf(class java.lang.String,int) throws NumberFormatException
simple   :public static java.lang.Integer java.lang.Integer.valueOf(int)
generic  :public static java.lang.Integer java.lang.Integer.valueOf(int)
modified :public static Integer valueOf(int)
simple   :public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String) throws java.lang.NumberFormatException
generic  :public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String) throws java.lang.NumberFormatException
modified :public static Integer valueOf(class java.lang.String) throws NumberFormatException
simple   :public int java.lang.Integer.intValue()
generic  :public int java.lang.Integer.intValue()
modified :public int intValue()
simple   :public static int java.lang.Integer.reverse(int)
generic  :public static int java.lang.Integer.reverse(int)
modified :public static int reverse(int)
simple   :static int java.lang.Integer.stringSize(int)
generic  :static int java.lang.Integer.stringSize(int)
modified :static int stringSize(int)
simple   :public static int java.lang.Integer.reverseBytes(int)
generic  :public static int java.lang.Integer.reverseBytes(int)
modified :public static int reverseBytes(int)
simple   :public byte java.lang.Integer.byteValue()
generic  :public byte java.lang.Integer.byteValue()
modified :public byte byteValue()
simple   :public double java.lang.Integer.doubleValue()
generic  :public double java.lang.Integer.doubleValue()
modified :public double doubleValue()
simple   :public float java.lang.Integer.floatValue()
generic  :public float java.lang.Integer.floatValue()
modified :public float floatValue()
simple   :public long java.lang.Integer.longValue()
generic  :public long java.lang.Integer.longValue()
modified :public long longValue()
simple   :public short java.lang.Integer.shortValue()
generic  :public short java.lang.Integer.shortValue()
modified :public short shortValue()
simple   :public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException
generic  :public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException
modified :public static int parseInt(class java.lang.String) throws NumberFormatException
simple   :public static int java.lang.Integer.parseInt(java.lang.String,int) throws java.lang.NumberFormatException
generic  :public static int java.lang.Integer.parseInt(java.lang.String,int) throws java.lang.NumberFormatException
modified :public static int parseInt(class java.lang.String,int) throws NumberFormatException
simple   :public static int java.lang.Integer.bitCount(int)
generic  :public static int java.lang.Integer.bitCount(int)
modified :public static int bitCount(int)
simple   :public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,java.lang.Integer)
generic  :public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,java.lang.Integer)
modified :public static Integer getInteger(class java.lang.String,class java.lang.Integer)
simple   :public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,int)
generic  :public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,int)
modified :public static Integer getInteger(class java.lang.String,int)
simple   :public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String)
generic  :public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String)
modified :public static Integer getInteger(class java.lang.String)
simple   :public static int java.lang.Integer.highestOneBit(int)
generic  :public static int java.lang.Integer.highestOneBit(int)
modified :public static int highestOneBit(int)
simple   :public static int java.lang.Integer.lowestOneBit(int)
generic  :public static int java.lang.Integer.lowestOneBit(int)
modified :public static int lowestOneBit(int)
simple   :public static int java.lang.Integer.numberOfLeadingZeros(int)
generic  :public static int java.lang.Integer.numberOfLeadingZeros(int)
modified :public static int numberOfLeadingZeros(int)
simple   :public static int java.lang.Integer.numberOfTrailingZeros(int)
generic  :public static int java.lang.Integer.numberOfTrailingZeros(int)
modified :public static int numberOfTrailingZeros(int)
simple   :public static int java.lang.Integer.rotateLeft(int,int)
generic  :public static int java.lang.Integer.rotateLeft(int,int)
modified :public static int rotateLeft(int,int)
simple   :public static int java.lang.Integer.rotateRight(int,int)
generic  :public static int java.lang.Integer.rotateRight(int,int)
modified :public static int rotateRight(int,int)
simple   :public static int java.lang.Integer.signum(int)
generic  :public static int java.lang.Integer.signum(int)
modified :public static int signum(int)
simple   :public static java.lang.String java.lang.Integer.toBinaryString(int)
generic  :public static java.lang.String java.lang.Integer.toBinaryString(int)
modified :public static String toBinaryString(int)
simple   :public static java.lang.String java.lang.Integer.toOctalString(int)
generic  :public static java.lang.String java.lang.Integer.toOctalString(int)
modified :public static String toOctalString(int)
simple   :private static java.lang.String java.lang.Integer.toUnsignedString(int,int)
generic  :private static java.lang.String java.lang.Integer.toUnsignedString(int,int)
modified :private static String toUnsignedString(int,int)

答案 3 :(得分:0)

感谢您的想法。我采取了一些你的建议并改变了一些事情。这是我的代码:

/ *     *显示给定类的方法。显示的项目取决于     *输入的选项。     *     * @param cl要显示的类     * /     public void方法(Class cl)     {         //获取类cl的方法         方法[] me = cl.getDeclaredMethods();

    // If all modifiers are selected, print all Methods
    if(allMods == true)
    {
        for(Method x : me)
        {            
            //System.out.println(INDENT + x);
            printMethod(x);
        }
    } 

    // Print Methods, only displaying those items with the modifiers that 
    // were selected
    else
    {
        for(Method x : me)
        {            
            String str = x.toString();

            if((str.startsWith("private") && p == true) ||
                (str.startsWith("public") && u == true) ||
                (str.startsWith("protected") && P == true))
            {
                //System.out.println(INDENT + x);
                printMethod(x);
            }

        }
    }
}

这是输出:

    public static int numberOfLeadingZeros(int)
public static int numberOfTrailingZeros(int)
public static int bitCount(int)
public boolean equals(Object)
public String toString()
public static String toString(int, int)
public static String toString(int)
public int hashCode()
public static int reverseBytes(int)
public volatile int compareTo(Object)
public int compareTo(Integer)
public byte byteValue()
public short shortValue()
public int intValue()
public long longValue()
public float floatValue()
public double doubleValue()
public static Integer valueOf(String)
public static Integer valueOf(int)
public static Integer valueOf(String, int)
public static int reverse(int)
static int stringSize(int)
public static String toHexString(int)
static void getChars(int, int, char[])
public static Integer decode(String)
public static int compare(int, int)
public static int parseInt(String)
public static int parseInt(String, int)
public static String toOctalString(int)
public static String toBinaryString(int)
private static String toUnsignedString(int, int)
public static Integer getInteger(String)
public static Integer getInteger(String, int)
public static Integer getInteger(String, Integer)
public static int highestOneBit(int)
public static int lowestOneBit(int)
public static int rotateLeft(int, int)
public static int rotateRight(int, int)
public static int signum(int)