public interface MyInteface {
public void func1();
public void func2();
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Reflect {
public MyInteface mMyInterface;
public void setReflect(MyInteface myInterface) {
mMyInterface = myInterface;
}
public void invokeMyfunc() {
Class<MyInteface> myInterface = (Class<MyInteface>) mMyInterface
.getClass();
Method m1;
try {
m1 = myInterface.getDeclaredMethod("myfunc");
m1.invoke(mMyInterface);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
MyInteface myInterface = new MyInteface() {
public void func2() {
System.out.println("func2");
}
public void func1() {
System.out.println("func1");
}
/**
* 自定义函数,不为外部所知,可以用来暗渡成仓...
*/
public void myfunc(){
System.out.println("myfunc");
}
};
Reflect reflect = new Reflect();
reflect.setReflect(myInterface);
reflect.invokeMyfunc();
}
}