【问题标题】:Java getter return type based on object type基于对象类型的Java getter返回类型
【发布时间】:2016-04-04 15:35:34
【问题描述】:

我想要达到的目标如下:

public class Foo {
    Object o;

    public Foo(Object o) { //takes object
        this.o = o;
    }

    public <T> T getO() { //the return type of this should be the object type
        return (T) o;
    }
}

例如:

Object o = "123"; // imagine this comes from external system and can be anything
Foo foo = new Foo(o);
String foo = foo.getO(); //returns String

我看到一些使用 Google Guava TypeToken 执行类似操作的示例,但无法获得我想要的行为。

【问题讨论】:

  • 如果 Foo 不是泛型类型,这是行不通的 - 编译器如何知道如何处理对 Foo.getO() 的调用?
  • 您需要使 Foo 通用或使用反射...这里有类似的东西吗? stackoverflow.com/questions/75175/…

标签: java generics reflection


【解决方案1】:

如果你让 Foo 具有正确的类型,你可以做你想做的事

public class Foo<T> {
   T data;

   public Foo(T d)
   {
      this.data = d;
   }

   public T getData()
   {
     return data;
   }
}

那么您的示例将作为:

Foo<String> foo = new Foo<>("123"); //passing String
String foo = foo.getData(); //return String

Foo<Float> foo = new Foo<>(123f); //passing float
float foo = foo.getData(); //return float

编辑:原问题略有更新。但是,基本问题仍然是 Java 方法必须声明其返回类型。如果可以通过扩展层次结构以某种方式使用covariant 返回,则可以接近。有Overriding a method with different return typesCan overridden methods differ in return type的例子。

您还可以考虑使用工厂模式来辅助该方法。所以会是

Foo foo = FooFactory.geetFoo(originalData);  // the specific foo would vary
String s = foo.getData();

【讨论】:

  • 也就是说不知道对象类型是不可能的?
  • @StoyanDekov 你是对的。如果在编译时不知道对象类型,就不可能在编译时知道返回值的对象类型。
  • @StoyanDekov,我看过你的例子。我了解您要达到的目标。由于示例已构建,因此不可能。 Java 方法必须声明其返回类型。我回答了你原来的问题。我正在更新以提供一个潜在的替代方案,但这并不完全符合您的要求。
  • @KedarMhaswade,你是对的,谢谢。我复制了原始示例并没有更新所有内容。进行编辑。
猜你喜欢
  • 2018-09-26
  • 2021-11-10
  • 2019-10-29
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
  • 1970-01-01
  • 2011-12-16
相关资源
最近更新 更多