是否有可用的解决方法..?
是的。有。从现有类中提取接口。
upd
如果你在某些特定的类中需要它,你可以写smt,比如
//interface that already exists
public interface IDomain {
String foo();
}
//your class
public class Domain implements IDomain{
public String foo(){
return "domain foo";
}
//method that doesn't placed in IDomain
public String bar(){
return "domain bar";
}
}
//So you need create new interface with bar()
//it can extend IDomain
public interface ExtendedIDomain extends IDomain {
public String bar();
}
//than your wrapper factory will be like this
public class Proxifier {
public static ExtendedIDomain getProxy(Domain obj) {
InvocationHandler ih = new InjectProxy( obj );
ClassLoader classLoader = InjectProxy.class.getClassLoader();
return (ExtendedIDomain) Proxy.newProxyInstance( classLoader, new Class[]{ExtendedIDomain.class}, ih );
}
static class InjectProxy implements InvocationHandler {
private final Domain domain;
private InjectProxy(Domain domain){
this.domain = domain;
}
public String invoke(Object proxy, Method method, Object[] args) throws Throwable{
for(Method m : domain.getClass().getMethods()){
//TODO: check signature(name, args etc) or implement some logic with annotations
if(m.getName().equals(method.getName())){
return "wrapped " + m.invoke(domain, args);
}
}
throw new IllegalArgumentException();
}
}
}
//test
public static void main(String[] args) {
ExtendedIDomain d = Proxifier.getProxy(new Domain());
System.out.println(d.foo());
System.out.println(d.bar());
}
如果你需要一些“通用”的东西,你应该使用AOP,正如lawrey allready所说@Peter。