1.准备接口
interface Animals {
fun sounds(name:String):String
fun eat(name: String):String
}
2.准备实现类
class Dog :Animals {
override fun sounds(name: String): String {
println("$name 再叫")
return "汪汪汪"
}
override fun eat(name: String): String {
println("$name 再吃" )
return "muniangmuniang"
}
}
3.准备代理 及 Main函数
fun main() {
val dog: Dog = Dog()
val proxy = Proxy.newProxyInstance(
dog.javaClass.classLoader, dog.javaClass.interfaces
) { proxy, method, args ->
println(method.name)
args?.forEach {
println(it.toString())
}
println("open")
method.invoke(dog, args[0])
println("stop")
null
} as Animals
proxy.sounds("张三")
proxy.eat("lisi")
println("xxx")
}
END 附上打印输出控制台
sounds
张三
open
张三 再叫
stop
eat
lisi
open
lisi 再吃
stop
xxx
Process finished with exit code 0
EXTRA再来点额外的。
public void main2() {
final Animals dog=new Dog();
//com.example.learnkt.proxy.Dog is not an interface ERROR 下面这个是执行不了的
Animals animals= (Animals) Proxy.newProxyInstance(Dog.class.getClassLoader(), new Class[]{Dog.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
method.invoke(dog,args[0]);
return null;
}
});
Animals animals2= (Animals) Proxy.newProxyInstance(Animals.class.getClassLoader(), new Class[]{Animals.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
method.invoke(dog,args[0]);
return null;
}
});
// animals.eat("baba"); //ERROR
animals2.sounds("hhsx");
}