2 回答
TA贡献56条经验 获得超455个赞
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class HelloWorld{
public static void main(String []args){
final Dog dog = new Dog();
SingleMan man = (SingleMan) Proxy.newProxyInstance(SingleMan.class.getClassLoader(), new Class[]{SingleMan.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Method m = dog.getClass().getMethod(method.getName(), method.getParameterTypes());
Object result = m.invoke(dog, args);
return result;
}
});
man.say();
}
public static class Dog {
public void say() {
System.out.println("汪!汪!");
}
}
public interface SingleMan {
void say();
}
}
TA贡献41条经验 获得超61个赞
Java其实一直有黑魔法的,至少目前为止这套API还没有被干掉,如果你还没听过,不妨去搜一下sun.misc.Unsafe
比如最简单的,你可以把checked exception当成runtime exception来用。
getUnsafe().throwException(new IOException());
添加回答
举报