Java 实例化接口或抽象类

1、 实例化接口:

某一天,我们想通过反射调用一个类的方法,但发现方法参数中有一个接口,我们都知道接口不能被实例化,这该怎么办呢?

举例:

public class TestLib {
public static final String TAG = "TestLib";

void myTest(MyInterface myInterface) {
Log.i(TAG, "myTest start executing ");
myInterface.doFail();
myInterface.doSucc();
}
}

我们想通过反射调用TestLib.myTest(...)方法,
public interface MyInterface {
void doFail();

void doSucc();
}
但参数是个接口,仔细一想,我们可以通过动态代理实现接口啊!
实现:
// Step one:
val TestLibClass = Class.forName("demo.apt.aptyyb.TestLib")
val TestLibObject = TestLibClass.newInstance()

// Step two:
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)

再看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")
}

}


最后Run,看结果:

I/TestLib: myTest start executing
I/MainActivity: doFail
I/MainActivity: doSucc

 
2、实例抽象类
上面通过动态代理在内存中实例化了接口,那么抽象类该如何处理呢?
2018年的某天,风和日丽,像往常一样开始码代码,生命不止,码码不息:
现在在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();
}
原来是一个抽象类啊!那么问题来了,如何通过反射调用含抽象类的方法呢?









猜你喜欢

转载自www.cnblogs.com/lzh-Linux/p/9149262.html