0

リフレクションを使用して指定されたクラスに関する情報を取得するクラスを作成しています。出力には完全修飾メソッド名が含まれていますが、出力に完全修飾名は必要ありません。

例を次に示します。それ以外の:

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);
    }
}

文字列を解析してクリーンアップすることはいつでもできますが、それはちょっとしたハックのようです。しかし、それを行うより良い方法はありません。

4

4 に答える 4

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 + ">";
        }
    }
}
于 2012-11-19T05:47:03.363 に答える
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 , )

私はあなたのニーズに合うようにビルド内の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)
于 2012-11-19T05:50:59.343 に答える
1

次のことを試してください。

System.out.println(x.toString().replaceAll("([\\w_$]+\\.)+", ""));
于 2012-11-19T05:44:33.827 に答える
0

アイデアをありがとう。私はあなたの提案のいくつかを取り、いくつかのことを変更しました。これが私のコードです:

/* * 指定されたクラスのメソッドを表示します。表示される項目は、入力したオプションによって異なります。* * @param cl 表示するクラス */ public void methods(Class cl) { // クラス cl のメソッドを取得 Method[] 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)
于 2012-11-19T20:36:01.160 に答える