我是java新手,我正在尝试使用泛型类型类来获取用户输入并将其在不同情况下转换为不同类型(包括Integer、String、Bigdecimal)。我这里有 3 个问题。
如果在声明类对象时将 T 设置为 String,我可以检查泛型类型的类字段成员是否是 String 的实例。
如果我可以测试 1,有什么方法可以将 String 值分配给泛型类型的字段成员?
是否可以根据声明时设置的T将用户输入转换为不同的类型,例如,如果T设置为Integer,那么类方法就会知道我需要使用Integer。 parseInt(user input) 来转换它然后将其存储到类字段成员中?
谁能对上述问题给出解决方案或一些提示吗?
下面是我的代码。如果这种方法不可能,有什么方法可以完成这项工作吗?
public class userInputReader<T> {
private T userInput;
public userInputReader()throws IOException
{
readUserInput();
}
private void readUserInput() throws IOException
{
BufferedReader userInputBReader = new BufferedReader(new InputStreamReader(System.in);
if(userInput instanceof String)
{
userInput = userInputBReader.readLine();
}
else if(userInput instanceof Integer)
{
userInput = Integer.parseInt(userInputBReader.readLine());
}
else if(userInput instanceof BigDecimal)
{
userInput = new BigDecimal(userInputBReader.readLine());
}
}
}
我是新来的,如果我所做的任何事情违反了这里的规则,请指出,谢谢!
最佳答案
您需要了解在源代码中看到的内容与在编译输出中看到的内容之间存在差异。
使用上面的代码即表示编写
final UserInputReader<String> reader = new UserInputReader<>();
就是这样。在该类之外很好,您可以看到该实例与 String
一起使用。类型。
然而在该类中,情况有点不同。
问题在于Java泛型类型的信息在编译期间被删除,因此编译后,UserInputReader
看起来像
public class UserInputReader {
private Object userInput;
...
Can I check if a class field member with generic type is an instance of for example String or not if you set the T as String when declaring the class object.
当然可以,但这与是否使用泛型类型完全无关。
If I can test 1, are there ways that I can assign String value to the field member with generic type?
正如您在上面的示例中看到的,类字段将变成
private Object userInput;
所以是的,您可以将任何您想要的内容分配给 Object
,它是万物之母。
Is it possible to convert the user input into different types according to the T that set when declare, for example, if the T is set to be Integer then the class method will know that I need to use Integer.parseInt(user input) to convert this and then store it into class field member?
您已经使用 instanceof
完成了此操作运算符。
但是,就是userInput
是 null
在分配它之前,您无法以任何有意义的方式比较其类型。
那些检查
if (userInput instanceof String)
else if (userInput instanceof Integer)
else if (userInput instanceof BigDecimal)
总是会产生 false
在那时候。你所做的基本上是
if (null instanceof String)
<小时/>
如果您仍然想在构造点决定要处理哪种类型的对象,唯一可能的方法是将 Class<?>
传递给构造函数。类型。
public class UserInputReader {
private final Class<?> clazz;
private Object userInput;
public userInputReader(final Class<?> clazz) throws IOException {
this.clazz = clazz;
readUserInput();
}
...
例如
final UserInputReader reader = new UserInputReader(String.class);
可以像这样使用
if (String.isAssignableFrom(this.clazz)) {
userInput = userInputBReader.readLine();
}
等等。
关于java - 如何使用泛型类型类获取用户输入并转换为所需类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55312213/