0
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;

    }
}
4

2 回答 2

2

由于类型擦除,这是完全不可能的。

你能做的最好的事情就是让调用者通过一个Class<T>.

于 2012-10-03T03:05:37.040 回答
0

也许您可以查看 com.google.inject.TypeLiteral ,因为它可以通过擦除来帮助您。它将保留原始(非通用)类型。

于 2015-03-04T00:34:15.277 回答