[英]Wrapping uneditable Singleton classes
我有一个混淆的jar文件中的SingletonA
和SingletonB
类。 它们没有实现相同的接口,也不是同一个超类的孩子,但它们确实具有相似的特征,这是原始程序员所遗漏的。
我希望能够将它们作为参数传递给这样的方法:
public void method(SingletonObject singleton) {
//do stuff with singleton
}
但是,我唯一能想到的就是这个:
public void method(Object singleton) {
if(singleton instanceof SingletonA) {
SingletonA singletonA = (SingletonA) singleton;
// do stuff with singletonA
}
else if(singleton instanceof SingletonB) {
SingletonB singletonB = (SingletonB) singleton;
//do exact same stuff with singletonB
}
else {
return;
}
}
由于最底层的例子很糟糕,我该怎么做才能让它看起来更像顶部。
如果您知道这两个不同的类存在某种方法,那么您可以使用反射
public void method(Object singleton) {
Class<?> clazz = singleton.getClass();
Method m;
try {
m = clazz.getDeclaredMethod("someCommonMethod");
//m.setAccessible(true);
m.invoke(singleton);
} catch (Exception e) {
e.printStackTrace();
}
}
组合也可以是一个选项:
class SingletonObject{
SingletonA a;
SingletonB b;
SingletonObject(SingletonA a, SingletonB b){
if(a==null && b==null){
throw InvalidArgumentException();
}
this.a = a;
this.b =b
}
public void callCommonMethod(){
if(a!=null){
a.callCommonMethod();
}else{
b.callCommonMethod()
}
}
}
所以你在一个类中组成单例对象,任何人都可以使用它而不知道它们背后是什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.