我把这个问题写成代码中的注释,我觉得这样比较容易理解。
public class Xpto{
protected AbstractClass x;
public void foo(){
// AbstractClass y = new ????? Car or Person ?????
/* here I need a new object of this.x's type (which could be Car or Person)
I know that with x.getClass() I get the x's Class (which will be Car or
Person), however Im wondering how can I get and USE it's contructor */
// ... more operations (which depend on y's type)
}
}
public abstract class AbstractClass {
}
public class Car extends AbstractClass{
}
public class Person extends AbstractClass{
}
有什么建议吗?
提前致谢!
答案 0 :(得分:5)
首先,BalusC是对的。
其次:
如果您根据类类型做出决定,那么您就不会让多态性发挥作用。
您的班级结构可能有误(例如Car和Person不应该在同一层级中)
你可以创建一个接口和代码。
interface Fooable {
Fooable createInstance();
void doFoo();
void doBar();
}
class Car implements Fooable {
public Fooable createInstance() {
return new Car();
}
public void doFoo(){
out.println("Brroooom, brooooom");
}
public void doBar() {
out.println("Schreeeeeeeekkkkkt");
}
}
class Person implements Fooable {
public Fooable createInstance(){
return new Person();
}
public void foo() {
out.println("ehem, good morning sir");
}
public void bar() {
out.println("Among the nations as among the individuals, the respect for the other rights means peace..");// sort of
}
}
稍后......
public class Xpto{
protected Fooable x;
public void foo(){
Fooable y = x.createInstance();
// no more operations that depend on y's type.
// let polymorphism take charge.
y.foo();
x.bar();
}
}
答案 1 :(得分:3)
如果类具有(隐式)默认的no-arg构造函数,那么您只需调用Class#newInstance()
即可。如果要获取特定的构造函数,请使用Class#getConstructor()
,其中将参数类型传递给它,然后在其上调用Constructor#newInstance()
。 蓝色代码实际上是链接,单击它们以获取Javadoc,它包含有关该方法的确切内容的详细说明。
要了解有关反思的更多信息,请转到Sun tutorial on the subject。