Вы можете загрузить байт из соответствующего класса внутри файла 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, нужно было добавить в classpath.
Вы могли бы взглянуть на то, как я использую их в плагин-потребительной случае:
HTH