次のコードは、クラス内のキー情報をASMバイトコードで読み出す方法for Hasorです.

2063 ワード

public static void main(String[] args) throws IOException {
        loadClassInfo(ResourcesUtils.getResourceAsStream(PluginsSupportModule.class.getName().replace(".", "/") + ".class"));
    }
    private Map<String, ClassInfo> classInfoMap = new WeakHashMap<String, ClassInfo>();
    private static void loadClassInfo(InputStream inStream) throws IOException {
        ClassReader classReader = new ClassReader(inStream);
        ClassInfo info = new ClassInfo();
        info.className = classReader.getClassName().replace('/', '.');
        info.superClass = classReader.getSuperName().replace('/', '.');
        info.interFaces = classReader.getInterfaces();
        for (int i = 0; i < info.interFaces.length; i++)
            info.interFaces[i] = info.interFaces[i].replace('/', '.');
        //packageName
        if (info.className.lastIndexOf(".") > 0)
            info.packageName = info.className.substring(0, info.className.lastIndexOf("."));
        //annos
        final ArrayList<String> annoStr = new ArrayList<String>();
        classReader.accept(new ClassVisitor(Opcodes.ASM4) {
            public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
                /** Ljava/lang/Object; java/lang/Object 。*/
                String annnoType = desc.substring(1, desc.length() - 1);
                annoStr.add(annnoType);
                return super.visitAnnotation(desc, visible);
            }
        }, ClassReader.SKIP_CODE);
        info.annos = annoStr.toArray(new String[annoStr.size()]);
        //
        System.out.println();
    }
    /** */
    private static class ClassInfo {
        /* */
        public String   className   = null;
        /* */
        public String   packageName = null;
        /* */
        public String   superClass  = null;
        /* */
        public String[] interFaces  = null;
        /* */
        public String[] annos       = null;
    }