【发布时间】:2014-06-09 00:59:42
【问题描述】:
[编辑:我重写了代码以进一步简化它并专注于手头的问题]
我正在处理这段特定的代码:
class SimpleFactory {
public SimpleFactory build() {return null}
}
class SimpleFactoryBuilder {
public Object build(final Class builderClazz) {
return new SimpleFactory() {
@Override
public SimpleFactory build() {
return new builderClazz.newInstance();
}
};
}
}
但是,return 语句中的构建器会触发错误“找不到符号 newInstance”。好像 builderClazz 没有被识别为类对象。
我怎样才能让它工作?
编辑:解决方案(感谢 dcharms!)
上面的代码是我正在处理的代码的部分简化。下面的代码仍然是简化的,但包含了所有涉及的组件,并且包含了 dcharms 提供的解决方案。
package com.example.tests;
interface IProduct {};
interface ISimpleFactory {
public IProduct makeProduct();
}
class ProductImpl implements IProduct {
}
class SimpleFactoryBuilder {
public ISimpleFactory buildFactory(final Class productMakerClazz) {
return new ISimpleFactory() {
@Override
public IProduct makeProduct() {
try {
// the following line works: thanks dcharms!
return (IProduct) productMakerClazz.getConstructors()[0].newInstance();
// the following line -does not- work.
// return new productMakerClazz.newInstance();
}
catch (Exception e) {
// simplified error handling: getConstructors() and newInstance() can throw 5 types of exceptions!
return null;
}
}
};
}
}
public class Main {
public static void main(String[] args) {
SimpleFactoryBuilder sfb = new SimpleFactoryBuilder();
ISimpleFactory sf = sfb.buildFactory(ProductImpl.class);
IProduct product = sf.makeProduct();
}
}
【问题讨论】:
-
你在哪里定义了
builder方法?需要导入吗? -
你的意思是,你在哪里定义
builder类.. -
是的@PaulHicks,我的错。感谢收看。
-
该参数的
Class类型肯定是java.lang.Class,而不是不同包中的同名类吗? -
您仍在使用
new。请重新阅读我的答案。
标签: java class symbols anonymous