1. Instantiate the interface:
One day, we want to call a method of a class by reflection, but we find that there is an interface in the method parameter, we all know that the interface cannot be instantiated, what should we do?
Example:
public class TestLib {
public static final String TAG = "TestLib";
void MyTest (MyInterface myinterface) {
LOG.I (TAG, "myTest start executing");
Myinterface.dofail ();
MYINTERFACE.DOSUCC ();
}
}
We want to call Testlib.mytest (...) through reflection. Method
Public interface MyInterface {
void Dofail ();
void Dosucc ();
}
But the parameter is an interface, think carefully, we can realize the interface through the dynamic agent!
Realize:
Step One:
Val testlibclass = Class.forName ("Demo.apt.aptyyb.TestLib")
Val testlibobject = Testlibclass.newinstance ()
Step:
Val Mytestmethod = Testlibclass.getdeclaredmethod ("MyTest",
Class.forName ("Demo.apt.aptyyb.MyInterface"))
Step Three:
Val interfaceobject = proxy.newproxyinstance (ClassLoader,
Arrayof<class<*>> (Class.forName ("Demo.apt.aptyyb.MyInterface")), Myinvoke ())
Step Four:
Mytestmethod.invoke (Testlibobject, Interfaceobject)
Then look at the definition of Myinvoke:
Inner class Myinvoke:invocationhandler {
Override Fun Invoke (Proxy:any, Method:method?, Args:array<out any>?) {
if (method?. Name.equals ("Dofail")) {
LOG.I (TAG, "Dofail")
}else if (method?). Name.equals ("DOSUCC")) {
LOG.I (TAG, "DOSUCC")
}
}
Last run, look at the result:
I/testlib:mytest Start executing
I/mainactivity:dofail
I/mainactivity:dosucc
2. Instance abstract class
The interface is instantiated in memory by a dynamic proxy, so what should the abstract class do?
One day in 2018, the weather, as usual to start code, life, code endless:
Now there's one more way in Testlib,
void Abstracttest (Myabstract myabstract) {
LOG.I (TAG, "abstracttest start executing");
Myabstract.dofail ();
MYABSTRACT.DOSUCC ();
}
What is the "myabstract"???
Public abstract class Myabstract {
void Dofail () {
}
abstract void dosucc ();
}
The original is an abstract class Ah! So the question is, how do you invoke the method with the abstract class through reflection?
Java instantiation Interface or abstract class