How do you change imports with Byte Buddy?

Deadly 提交于 2019-12-14 02:06:50

问题


I'd like to change the imports of a class so that they point to a different package. Byte Buddy docs don't give much info on how one can achieve this. This is what I have so far:

 
public class ProxyPlugin implements net.bytebuddy.build.Plugin {
    public DynamicType.Builder apply(DynamicType.Builder builder, TypeDescription typeDescription) {
        return builder.name(typeDescription.getPackage().getName() + ".proxy."  + typeDescription.getSimpleName());

    }

    public boolean matches(TypeDescription typeDefinitions) {
        return true;
    }
}

My goal is to change some package prefix names so that they have ".proxy" appended to them. Note that I only need to change method signatures since the targets are interfaces.


回答1:


I found a solution. Turns out Byte Buddy has a convenience class called ClassRemapper to achieve exactly what I want:

public class ProxyPlugin implements net.bytebuddy.build.Plugin {
    public DynamicType.Builder apply(DynamicType.Builder builder, TypeDescription typeDescription) {
        DynamicType.Builder proxy = builder.name(typeDescription.getPackage().getName() + ".proxy." + typeDescription.getSimpleName());

        proxy = proxy.visit(new AsmVisitorWrapper() {
            public int mergeWriter(int flags) {
                return 0;
            }

            public int mergeReader(int flags) {
                return 0;
            }

            public ClassVisitor wrap(TypeDescription instrumentedType, ClassVisitor classVisitor, int writerFlags, int readerFlags) {
                return new ClassRemapper(classVisitor, new Remapper() {
                    @Override
                    public String map(String typeName) {
                         if (typeName.startsWith("org/example/api") && !typeName.contains("/proxy/")) {
                            return typeName.substring(0, typeName.lastIndexOf("/") + 1) + "proxy" + typeName.substring(typeName.lastIndexOf("/"));
                        } else {
                            return typeName;
                        }
                    }
                });
            }
        });

        return proxy;
    }

    public boolean matches(TypeDescription typeDescription) {
        return true;
    }
}


来源:https://stackoverflow.com/questions/39742821/how-do-you-change-imports-with-byte-buddy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!