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;
}
有没有其他方法可以做到这一点?Java通用类型返回T
我只想做这样的事情: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;
}
}
你只能在C#中做到这一点。 – SLaks
相关:http://stackoverflow.com/questions/9950800/java-generic-string-to-t-parser – BalusC
你的功能的用户通过它是通用的获得什么?换句话说,为什么用户不需要'int x = Integer.parseInt(“2”);'当他需要'int','Foo f = Foo.valueOf(“fooData {2,3}” )'当他需要'Foo'等时?在我看来,调用者需要知道具体的类型,逻辑会根据具体的类型做不同的事情,所以在泛型中没有太大的收获。 –