A
A
all230819922015-06-30 23:28:42
Java
all23081992, 2015-06-30 23:28:42

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

2 answer(s)
A
Aleksandr Koscheev, 2015-07-02
@ru-alxr

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.

A
angry_cellophane, 2015-07-01
@angry_cellophane

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());
    }
}

Unsafe is a specific thing, defineClass under android may not exist. In this case, you can get the current classloader, replace the parent loader in it with your own. Its loader calls the private method URLClassLoader#defineClass , which does the same thing as the code above.
In general, some kind of perversion. It's not worth it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question