[编辑:我重写了代码以进一步简化它并专注于手头的问题]
我正在处理这段特定的代码:
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
是一个Class
对象。请尝试以下操作:
return builder.getConstructors()[0].newInstance(anInput);
注意:这假设您正在使用第一个构造函数。您也许可以使用 getConstructor()
但我不确定它对于泛型类型的行为如何。
关于java - 在内部类中找不到类型符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23257093/