Reputation: 1
Hello to explain what i am trying to do its best i show you
public class Main {
public enum Types{
ONE(One.class),TWO(Two.class),THREE(Three.class);
Class<?> type;
private Types(Class<?> type) {
this.type = type;
}
}
public class Manager {
ArrayList<Number> numbers = new ArrayList<>();
public void Load() {
//THIS IS WHERE I AM STUCK
//I know it can be done like this below to add them in to the array with the types
numbers.add((One) new Number());
numbers.add((Two) new Number());
numbers.add((One) new Number());
numbers.add((Three) new Number());
//But i want to be able to add them like this.
numbers.add(Types.ONE.type.newInstance());
}
public void Run() {
if (numbers.isEmpty()) {
Load();
}
for (Number n : numbers) {
n.call();
}
}
}
public class Number {
public void call() {
}
}
public class One extends Number {
@Override
public void call() {
}
}
public class Two extends Number {
@Override
public void call() {
}
}
public class Three extends Number {
@Override
public void call() {
}
}
}
If you look for the comments in the code i am trying to add the "Number" to the array but with is sub class.
Now this is a example in the application i want it for the objects have parameters in the constructors. Can any one point me in the right direction.
The reason i just do not add them by using .add is in the real application there are 100s of objection to add to the array list and when i get these object there stored with there enum to show what type they are. Also these objects get changed regularly.
Upvotes: 0
Views: 55
Reputation: 178263
Currently the variable type
in Types
is of type Class<?>
. This Class
object could represent any class object, which is not necessarily in the Number
class hierarchy you've created.
Any object returned by newInstance
could be of any type, so it can't be allowed by the compiler to be sent to an ArrayList<Number>
as a parameter; it might not match.
Add an upper bound to the type of type
:
enum Types{
ONE(One.class),TWO(Two.class),THREE(Three.class);
// add ? extends Number here
Class<? extends Number> type;
// add ? extends Number here
private Types(Class<? extends Number> type) {
this.type = type;
}
}
You'll still have to catch all of the reflection-related exceptions: IllegalAccessException
and InstantiationException
.
Also note that in Java 9+, Class.newInstance
is deprecated; you should replace that call with
getDeclaredConstructor().newInstance()
which also throws NoSuchMethodException
and InvocationTargetException
.
Upvotes: 2