![](/img/trans.png)
[英]javassist throws ClassNotFoundException when loading external classes from jar
[英]Parse classes from jar using javassist
我是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)));
}
您可以通過以下代碼從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);
要在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);
}
}
也許可以減少一些代碼,但這就是我從JAR文件加載字節並將其加載到Javassist中的方式。 由於最終的依賴關系,JAR文件已加載到Javassist類路徑。 另外,出於某種原因,我需要使用Javassist檢測的類也必須添加到類路徑中。
您可能會看看我如何在插件用例中使用它們:
高溫超導
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.