Reputation: 177
I want to know if there is a way to do this:
String **type** = "Player"
ArrayList<**type**> players = new ArrayList();
What I mean is defining an object type with a variable String. I put "player" and it can just be Player
here, but what about a method that you can introduce a variable type to? Something like this:
public static void main (String[] args)
{
system.out.println("Select a type that u wanna make an array of");
system.out.println("1. Player");
system.out.println("2. Team");
Scanner in = new Scaner (System.in);
createArray(in.next());
}
public static void createArray(String **type**)
{
ArrayList<**type**> x = new ArrayList();
}
Is that possible?
Upvotes: 2
Views: 87
Reputation: 1519
There is no reason for doing this:
Generic types are only for compilation time type checking you need to understand this, they are not needed for what you are doing (determining the generic type at runtime).
You can simply do
List objects = new ArrayList();
and proceed to put any type into it but you will obviously have to cast the objects to the correct type before using them after taken out of the list.
Upvotes: 0
Reputation: 10891
I am pretty sure it is possible with annotations and a custom annotation processor (but probably not a good idea).
Then your code would look like
@StringlyType String type="Player"
and you would would have to write a custom annotation processor that whenever it encounters a @StringlyType
annotation creates a class as the other answers suggest.
But What is the Point?
Disclaimer: I have not actually tried any of this; nor do I intend to. So I can not guarantee it works.
Upvotes: 1
Reputation: 106430
Run away from Stringly-typed thinking and simply create your own class to capture all of the information you would want about a player.
public class Player {
// fields, methods to describe a player
}
public class Team {
// fields, methods to describe a team
}
Then, your ArrayList
would work as you expect it to.
List<Player> players = new ArrayList<>();
List<Team> teams = new ArrayList<>();
As a side note: your current code structure would only create the list in that method and it wouldn't be available afterwards. If you want it back, you'd have to return ArrayList<Player>
, or alternatively, declare it inside of main
when you go to use it.
Upvotes: 8