简体   繁体   English

引入String以定义类型

[英]Introducing a String to define a type

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. 我的意思是定义一个带有变量String的对象类型。 I put "player" and it can just be Player here, but what about a method that you can introduce a variable type to? 我把“播放器”放在这里,它可以只是Player ,但是你可以引入变量类型的方法呢? 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? 那可能吗?

Run away from Stringly-typed thinking and simply create your own class to capture all of the information you would want about a player. 远离 Stringly类型的思维,只需创建自己的类来捕获您想要的有关玩家的所有信息。

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. 然后,您的ArrayList将按预期工作。

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. 如果你想要它,你必须返回ArrayList<Player> ,或者当你去使用它时,在main声明它。

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. 并且您将不得不编写一个自定义注释处理器,只要遇到@StringlyType注释,就会像其他答案所建议的那样创建一个类。

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. 所以我不能保证它有效。

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. 并继续将任何类型放入其中,但显然必须将对象转换为正确的类型,然后在从列表中取出之后使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM