Answer the question
In order to leave comments, you need to log in
Is it possible to override a method in a library?
Hello.
I am developing a project in android studio. The project includes a library in which you want to change the class class1. Is it possible to somehow redefine the library class class1 in overclass1 , so that there would be no changes in the original class1, but the library classes used my overridden overclass1 class?
Answer the question
In order to leave comments, you need to log in
Create your class by inheriting from the library class.
Override the methods you need.
Use the generated class.
PS provided that the class is not final and the desired method is not final.
1. Google the library loading order. Perhaps there is a chance to override the library class with your own.
2. Use reflection
public class Main {
static {
try {
Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
Unsafe U = (Unsafe) unsafeField.get(null);
File f = new File("C:\\dev\\tmp\\TestA.class");
FileInputStream input = new FileInputStream(f);
byte[] content = new byte[(int)f.length()];
input.read(content);
input.close();
U.defineClass("com.company.a.TestA", content, 0, content.length, Main.class.getClassLoader(), Main.class.getProtectionDomain());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
ClassLoader loader = Main.class.getClassLoader();
System.out.println(loader.getParent());
System.out.println(new TestA());
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question