Get callers method (java.lang.reflect.Method)

后端 未结 4 463
礼貌的吻别
礼貌的吻别 2020-12-08 16:53

I would like to get the calling method java.lang.reflect.Method. NOT the name of the method.

Here is an example how to get the callers

4条回答
  •  渐次进展
    2020-12-08 17:13

    Here is a modified version of Sean Patrick Floyd's posted method for getting a Java Class from an ASM Type. It fixes a problem with multidimensional arrays and another problem with classes loaded by other classloaders.

    public static Class getClassFromType(Class clazz, final Type type) throws ClassNotFoundException{
        Class javaType = null;
        switch( type.getSort() ) {
            case Type.VOID      : javaType = Void.TYPE; break;
            case Type.BOOLEAN   : javaType = Boolean.TYPE; break;
            case Type.CHAR      : javaType = Character.TYPE; break;
            case Type.BYTE      : javaType = Byte.TYPE; break;
            case Type.SHORT     : javaType = Short.TYPE; break;
            case Type.INT       : javaType = Integer.TYPE; break;
            case Type.FLOAT     : javaType = Float.TYPE; break;
            case Type.LONG      : javaType = Long.TYPE; break;
            case Type.DOUBLE    : javaType = Double.TYPE; break;
            case Type.ARRAY     : javaType = Array.newInstance( getClassFromType( clazz, type.getElementType()), new int[type.getDimensions()] ).getClass(); break; 
            case Type.OBJECT    : javaType = Class.forName( type.getClassName(), false, clazz.getClassLoader() ); break;
        }
        if ( javaType != null ) return javaType;
        throw new ClassNotFoundException( "Couldn't find class for type " + type );
    }
    

提交回复
热议问题