objeto construye una clase de objetos en java

There is a super class, A, and there are many subclasses, B,C,D... people can write more subclasses. Each of the class have the method dostuff(), each is different in some way.

I want an object that constructs any object that belong to A or any of it's subclass.

For example I can pass the name of the subclass, or a object of that class, and it will construct another object of the class.

Of course I can write

A construct(A var){
    stuff = var.dostuff();
    domorestuff(stuff)
    return new A(stuff);
}

B construct(B var){
    stuff = var.dostuff();
    domorestuff(stuff)
    return new B(stuff);
}

C construct(C var){
    stuff = var.dostuff();
    domorestuff(stuff)
    return new C(stuff);
}

but this is not efficient. I have to write a few new lines every time I make a new subclass.

It seems I can't use generics either. Because I can't use dostuff() on objects not in any of the subclass of A.

¿Que debería hacer en esta situación?

preguntado el 09 de enero de 11 a las 08:01

2 Respuestas

Puedes usar la reflexión.

public static <T extends A> T construct(Class<T> tClass) {
    T t = tClass.newInstance();
    t.doStuff();
    moreStuff();
    return t;
}

You may need to cast and catch exceptions, but that is the basic idea.

Respondido el 09 de enero de 11 a las 11:01

This is great. What if I want to use t's constructor? - Chao Xu

That uses the default constructor. if you want to use another constructor you need to use getConstructor() - Peter Lawrey

You should implement factory pattern. Your implementation will use Class.forName(className).

public A create(String className) throws Exception {
    return Class.forName(className).newInstance();
}

Respondido el 09 de enero de 11 a las 11:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.