欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

下面代码是通过ASM 字节码的形式读取类中关键信息方法 for Hasor

程序员文章站 2022-04-18 18:47:38
...
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;
    }



转载于:https://my.oschina.net/ta8210/blog/190853