【问题标题】:Java Generic TypeOf Return TJava Generic TypeOf 返回 T
【发布时间】:2012-09-23 23:01:07
【问题描述】:
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&lt;int&gt;();

它需要一个字符串并将其转换为&lt;Type&gt;

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;

    }
}

【问题讨论】:

  • 你的函数的用户通过它是通用的获得了什么?换句话说,为什么用户在需要int 时不直接使用int x = Integer.parseInt("2");,在需要Foo 时使用Foo f = Foo.valueOf("fooData{2,3}") 等等?在我看来,调用者需要知道具体类型,并且逻辑会根据具体类型做一些不同的事情,所以它是通用的并没有太大的好处。
  • 嗯,我是这个类的唯一用户,我想知道我是否可以这样做。目前,我创建了一个控制台类,我想将字符串转换为任何类型。在 C++ 中,我通常这样做:` template inline T ToNumber(const std::string &Text){std::istringstream SS(Text ); T 结果; return (SS >> Result ? Result : 0);}` 我也想用 Java 来做 ={
  • 我编辑了这个问题,以便您可以看到我在 C++ 中所做的以及我在 Java 中尝试的内容,但下面有人说这是不可能的。我想我会放弃它..

标签: java


【解决方案1】:

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

最好让调用者传递Class&lt;T&gt;

【讨论】:

  • 啊,好的,谢谢。有点失望,因为我刚刚学习 Java,这是我首先想到的事情之一。铸件。但我想明确地这样做是可以的。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2016-11-13
    • 2011-09-23
    • 2011-01-01
    • 1970-01-01
    • 2023-03-08
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多