I am working on a project that requires the use of a large number of objects of classes extending a particular abstract class. Instantiating manually requires a call to each object's individual constructor, which is starting to pollute my client class.
The raw code from the project is too lengthy to post on this site, so I have a simplified example below:
Suppose there is an abstract class called Letter:
public abstract class Letter{
String letter;
}
And 26 individual letter classes that extend the Letter abstract class:
public class A extends Letter{
this.letter = "A";
}
public class B extends Letter{
this.letter = "B";
}
... and so on
This is where I seek help - There is a client class called Alphabet:
public class Alphabet{
public List<Letter> getLetters(){
List<Letter> letters = new ArrayList<>();
A a = new A();
B b = new B();
C c = new C();
list.add(a);
list.add(b);
list.add(c);
...the list goes on
return letters;
}
}
As you can see, it is not ideal to instantiate each letter manually. I am looking for a way to create a list of class objects dynamically at runtime.
Perhaps something similar to this:
public class Alphabet{
public List<Letter> getLetters(){
List<Letter> letters = getAllClassesExtending(Letter.class);
return letters;
//list would then contain A,B,C,D,E,F,G, etc.
}
}
I ultimately want to be able to create a new class and have it automatically added to a list of objects in the client class, without needing to modify the client class (e.g. I do not want to explicitly reference each letter class in the client class).
Aucun commentaire:
Enregistrer un commentaire