Tuesday 15 September 2015

java - How can I automatically put subclasses in an ArrayList? -


I have a superclass, and then there are several subclasses, such as:

  Public abstract class A {public abstract int getValue (); } Public category B is expanded {Public Entity Value () {Return 1; }} Public category C is a comprehensive {public int getValue () {123 123; }} Public class D is expanding to a {public-cum-claim () {return 15234; }}   

In this there are about 100 or so sub classes. I also have a manager:

  Public class manager {public stable Array list & lieutenant; A & gt; List = New Arrestist & lt; A & gt; (); }   

How can I add an example of all the sub-squares of "magical" to a without having to manually Can I make an example of a single subclass and add it to the list? Maybe using an initial block?

Edit

It is not important how I list in manager . I have edited it to stabilize.

(Second attempt - my first attempt was on the basis of misunderstanding.)

I am assuming what you want to do (static) list which is:

  • is an example of every subclass,
  • has been created and from time Next, and
  • In each subclass does not include an example of adding / adding code to the list.

    First of all, an initializer block will not do this. An example initializer is run when you make an example ... and for doing something like this, the new class (i.e., for each subclass) is to be.

    I think the only viable approach is to write some hairy reflective code:

    • Goes on all squares on the squares again,
    • Each loads using class.forName () ,
    • Reflects to see if a class of A is a class,
    • If so, then reflects the class non-RGS constructor and the resultant example in the "list".

      This (IMO) is very Hummy !! And it's going to be expensive ... as long as you can limit the "package location", which requires the discovery of these subclasses.


      Actually, it can be a problem that will be better resolved by using enum ... especially if behavior in subclasses There are no differences that different law enforcement (for example your getValue () method can only return a personal variable ... using a constructor You can start.) See the answers of Paul Belora.

      (This is the case which will require some examples of some sub-classes to prevent it from being implemented. It is not possible with enums .)

No comments:

Post a Comment