Java-getConstructor()?
我把这个问题写在代码中作为注释,我认为这样更容易理解Java-getConstructor()?,java,reflection,getconstructor,Java,Reflection,Getconstructor,我把这个问题写在代码中作为注释,我认为这样更容易理解 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)
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{
}
有什么建议吗
提前谢谢 如果该类有一个(隐式的)默认无参数构造函数,那么您可以调用它。如果您想要获得一个特定的构造函数,那么使用其中的参数类型,将参数类型传递给并调用它。蓝色的代码实际上是链接,单击它们可以获得Javadoc,它包含了关于该方法具体作用的详细解释
要了解有关反射的更多信息,请访问。首先,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我同意使用工厂方法创建新实例。它有点像
clone
,只是它返回一个空白而不是一个副本。@Chris:是的,clone也可以使用,当您在运行时之前对对象一无所知时(这是Java中的速率,您至少知道它是某种类型的可食对象),但当您有:object o=???;Object copy=o.clone()
可能很有用。不幸的是,由于Object.clone
受到保护,因此对未知类型的对象执行此操作的唯一方法是通过反射调用clone
:-如果你要使用反射,你也可以用工厂方法,甚至构造器来反射-P@Chris:但类型部分未知。它是一个可食/抽象类,可以将clone()重新定义为public。