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;
}
Is there any other way that I can do this?
I just want to do something like: int X = Foo.Convert<int>();
Where it takes a string and converts it to <Type> <—– That. I tried:
public T Convert()
{
}
But I searched everywhere and Java doesn’t have a typeof function :S Basically trying to convert a string from the user to a data type.
EDIT.. I’m asking because in C++ I usually do:
template <typename T>
inline T ToNumber(const std::string &Text){std::istringstream SS(Text); T Result; return (SS >> Result ? Result : 0);}
I wanted to know if in Java I can do that.. I was using it like:
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;
}
}
Due to type erasure, that is completely impossible.
The best you can do it have the caller pass a
Class<T>.