例如我在类BugReportFactory中有以下方法:
public static void addFactoryImpl(Class impl) { }
我想通过以下方式从另一个类调用此方法:
BugReportFactory.addFactoryImpl(new BugReportFactoryAndroid());
它表示以下Argument不适用于Class类。
有谁可以说出我的错误?
还有一个问题:
private static IBugReportFactory INSTANCE = null;
public static void addFactoryImpl(Class impl) {
INSTANCE = (IBugReportFactory)impl;
}
但是它显示错误,指明你不能将类转换为对象?
答案 0 :(得分:5)
尝试以下操作,Object
课程有getClass()
方法
BugReportFactory.addFactoryImpl(new BugReportFactoryAndroid().getClass());
或者
BugReportFactory.addFactoryImpl(BugReportFactoryAndroid.class);
将完成这项工作。
还有一个问题:
private static IBugReportFactory INSTANCE = null; public static void addFactoryImpl(Class impl) { INSTANCE = (IBugReportFactory)impl; }
但它显示错误,指明您无法投射
类是不同的实例是不同的。将您的INSTANCE
变量类型更改为Class
。
private static Class INSTANCE = null;
public static void addFactoryImpl(Class impl) {
INSTANCE = impl;
}
Class是实例的蓝色打印。您无法将实例分配给类引用。两者都是两回事。
答案 1 :(得分:4)
BugReportFactory.addFactoryImpl(BugReportFactoryAndroid.class);
答案 2 :(得分:1)
Class是对象的某种蓝图。
当您致电new X()
时,您会创建class X
的新对象,这意味着您在 X 蓝图之后构建了一个新类。
在您的情况下,需要蓝图,因此您需要放置BugReportFactoryAndroid.class
在http://www.programmerinterview.com/index.php/java-questions/difference-between-object-and-class/
了解详情答案 3 :(得分:1)
您有两种选择:
BugReportFactory.addFactoryImpl(BugReportFactoryAndroid.class);
或者:
BugReportFactory.addFactoryImpl((new BugReportFactoryAndroid()).getClass());
我个人更喜欢第一个。
答案 4 :(得分:1)
(ObjectInstance).getClass()或(类名).class
答案 5 :(得分:1)
如果要在方法中传递类,则调用代码为:
BugReportFactory.addFactoryImpl(BugReportFactoryAndroid.class);
如果您确实想要传递此类的实例,那么您的方法签名应更改为:
public static void addFactoryImpl(Object impl) { }
OR
public static <T> void addFactoryImpl(T impl) { }
答案 6 :(得分:1)
实际上我并不认为你想传递Class类作为参数。这是一个用于反射目的的特殊类。
对于Abstract Factory设计模式,通常您有一个描述工厂API的通用接口,以及此接口的多个实现:
public interface BugReportFactory {
public A createA();
public B createB();
}
public class BugReportFactoryAndroid implements BugReportFactory {..}
public class BugReportFactoryIOS implements BugReportFactory {..}
调用工厂方法的类可能如下所示:
public class Foo {
private List<BugReportFactory> factories = new ArrayList<BugReportFactory>();
public void addFactoryImpl(BugReportFactory factory) {
factories.add(factory);
}
public void createAll() {
for (BugReportFactory f : factories) {
A a = f.createA();
B b = f.createB();
...
}
}
}
答案 7 :(得分:1)
最后我找到了解决问题的方法:如下:
private static IBugReportFactory INSTANCE = null;
public static void addFactoryImpl(Class<?> impl) {
Object factoryImpl = null;
try {
factoryImpl = impl.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
INSTANCE = (IBugReportFactory) factoryImpl;
}
如果你想调用这个方法,就像这样:
BugReportFactory.addFactoryImpl(BugReportFactoryAndroid.class);
感谢大家的支持和帮助。