Reputation: 43
I am trying to make a class loader which transforms the class bytes of the class being loaded using some kind of class transformer.
Suppose I have the following code:
static class Test {
void foo();
}
void test() {
ClassLoader transformingLoader = transformingClassLoader(..., this.getClass().getClassLoader(), ...);
Class<?> klass = Class.forName("test.package.Tests$TestClass", true, loader);
// I want to use the class easily here, but using it like this
// will cause it to load a new instance of the class, ignoring the already
// defined class by the transforming class loader and so all the transformations.
TestClass test1 = new TestClass();
test2.foo();
// Using something like this doesn't work either, it throws a ClassCastException
// because both classes are different from different loaders
TestClass test2 = (TestClass) klass.newInstance();
}
How could I make this work? I have tried using an interface like:
interface Test {
void foo();
}
static class TestClass implements Test {
// ...
}
void test() {
ClassLoader transformingLoader = ...
Class<?> klass = Class.forName("test.package.Tests$TestClass", true, loader);
// This leads to another ClassCastException though, because the transforming
// class loader defines it's own version of the Test interface.
Test test = (Test) klass.newInstance();
test.foo();
}
This is my current code for the transforming class loader: pastes.dev
So how could I fix these issues? I think most of the issues would be fixed if the class loader properly used already loaded classes when available but it doesn't seem like it does.
Upvotes: 0
Views: 82