[英]Parse classes from jar using javassist
I'm noob in javassist. 我是javassist的菜鸟。 Anyone can give the sample how to load classes from jar and save them using javassist? 任何人都可以给示例提供如何从jar加载类并使用javassist保存它们的方法吗?
jar = new JarFile(fileName);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = (JarEntry) entries.nextElement();
if(jarEntry == null)
break;
if(jarEntry.getName().endsWith(".class")) {
// ??????
} else {
resources.add(new RResource(jarEntry.getName(), jar.getInputStream(jarEntry)));
}
You can load the bytes from the respective class inside the JAR file via the code below: 您可以通过以下代码从JAR文件中的相应类加载字节:
JarFile jarFile = new JarFile(file);
// lets get a reference to the .class-file contained in the JAR
ZipEntry zipEntry = jarFile.getEntry(className.replace(".", "/")+".class");
if (zipEntry == null) {
jarFile.close();
return null;
}
// with our valid reference, we are now able to get the bytes out of the jar-archive
InputStream fis = jarFile.getInputStream(zipEntry);
byte[] classBytes = new byte[fis.available()];
fis.read(classBytes);
To load the bytes in javassist you can do the following stuff: 要在javassist中加载字节,您可以执行以下操作:
ClassPool cp = ClassPool.getDefault();
cp.insertClassPath(new ClassClassPath(this.getClass()));
ClassPath cp1 = null;
ClassPath cp2 = null;
// add the JAR file to the classpath
try {
cp1 = cp.insertClassPath(jarFile.getAbsolutePath());
} catch (NotFoundException e1) {
e1.printStackTrace();
return null;
}
// add the class file we are going to modify to the classpath
cp2 = cp.appendClassPath(new ByteArrayClassPath(className, classBytes));
byte[] modifiedBytes;
try {
CtClass cc = cp.get(className);
// skip instrumentation if the class is frozen and therefore
// can't be modified
if (!cc.isFrozen()) {
// do your javassist stuff here
}
modifiedBytes = cc.toBytecode();
} catch (NotFoundException | IOException | CannotCompileException | ClassNotFoundException e) {
handleException(e);
} finally {
// free the locked resource files
cp.removeClassPath(cp1);
cp.removeClassPath(cp2);
}
// write your modified bytes somewhere
if (modifiedBytes.length > 0) {
try(FileOutputStream fos = new FileOutputStream("pathname")) {
fos.write(modifiedBytes);
}
}
Maybe some of the code can be reduced, but this is how I load bytes from a JAR file and load them into Javassist. 也许可以减少一些代码,但这就是我从JAR文件加载字节并将其加载到Javassist中的方式。 The JAR file is loaded to the Javassist classpath due to eventual dependencies. 由于最终的依赖关系,JAR文件已加载到Javassist类路径。 Also the class which I instrument with Javassist needed to be added to the classpath for some reason. 另外,出于某种原因,我需要使用Javassist检测的类也必须添加到类路径中。
You might have a look at how I use them in a plugin-use-case: 您可能会看看我如何在插件用例中使用它们:
HTH 高温超导
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.