public Object Convert(Class<T> Type) {
if (Type == Integer.class) {
return Integer.parseInt(DataInfo);
} else if (Type == String.class ) {
return DataInfo;
} else if (Type == Double.class) {
return Double.parseDouble(DataInfo);
}
return null;
}
还有其他方法可以做到这一点吗?
我只想做类似的事情: int X = Foo.Convert<int>();
它需要一个字符串并将其转换为<Type>
<----- 那。我试过:
public T Convert()
{
}
但是我到处搜索,Java 没有 typeof 函数:S 基本上试图将字符串从用户转换为数据类型。
编辑..我问是因为在 C++ 中我通常这样做:
template <typename T>
inline T ToNumber(const std::string &Text){std::istringstream SS(Text); T Result; return (SS >> Result ? Result : 0);}
我想知道在Java中我是否可以做到这一点..我像这样使用它:
package test;
import java.io.*;
import java.util.Scanner;
public class Data<T> {
private String DataInfo;
public String ReadBuffer() throws IOException {
BufferedReader Buffer = new BufferedReader(new InputStreamReader(System.in));
return (DataInfo = Buffer.readLine());
}
public String ReadConsole() {
Console Con = System.console();
return (DataInfo = Con.readLine());
}
public String Read() {
Scanner Reader = new Scanner(System.in);
return (DataInfo = Reader.next());
}
public Object Convert(Class<T> Type) {
if (Type == Integer.class) {
return Integer.parseInt(DataInfo);
} else if (Type == String.class ) {
return DataInfo;
} else if (Type == Double.class) {
return Double.parseDouble(DataInfo);
}
return null;
}
}