我有一个抽象类Tool
,它由Hammer
,Screwdriver
等各种类子类化。
Tool
有一个带参数的构造函数
Tool(String name, double weight, double length)
然后我想在另一个类ToolUser
中,从传递给它的Tool
类中创建对象。
class ToolUser {
void createTool(***pass the Tool somehow here***) {
for (int i=1; i<10; i++) {
// create Tool object from passed Tool Class
// could be Hammer, Screwdriver, etc. whatever was passed
}
// ToolUser will then use the instantiated objects as
// Tool objects.. it doesn't care if they are Hammers,
// Screwdrivers or anything else.. it will just access them as
// a Tool object
}
}
我无法弄清楚如何将Hammer
传递给createTool(Class toolClass)
,原因是因为java编译器抱怨使用子类..
这可能以某种方式使用Reflection或Lambda表达式吗?
我还想以某种方式传递参数数据(权重和长度),以便我可以使用这些参数实例化Class - 如果可能的话。
任何人都有任何想法如何做到这一点..我对lambda表达式一无所知,我使用Reflection的尝试都失败了。
答案 0 :(得分:1)
听起来你需要一个ToolFactory
类来根据参数创建特定的Tool
子类。
因此ToolUser
会使用ToolFactory
e.g。
class ToolFactory
{
// create a screwdriver
static Tool createScrewdriver();
// create a hammer
static Tool createHammer();
// figure out what sort of tool the user wants and create it
static Tool createSomeTool(int width, int height, int weight);
}
另一种方法是工厂界面:
interface ToolFactory
{
Tool createTool(int length, int weight);
}
class ToolUser
{
void createTool(ToolFactory factory)
{
for (int i=1; i<10; i++) {
Tool t = factory.createTool(i, i*2);
并匿名传递给方法:
createTool(new ToolFactory {
Tool createTool(int length, int weight) {
return new Screwdriver(int length, int weight);
}
});
答案 1 :(得分:1)
正如我从问题中理解的那样,你需要根据类型在方法中创建一个实例,实现这一点的一种方法是Reflection
void createTool(Class<? extends Tool> clazz) { // allow Tool and its subtypes
// subtypes should have constructors matching this signature
Tool tool = clazz.getConstructor(String.class,double.class,double.class)
.newInstance("name", weight,length);
// deal with exceptions...
}
你可以这样称呼它
createTool(Hammer.class);
createTool(Screwdriver.class);