泛型仅定义为返回类型

泛型仅定义为返回类型

本文介绍了Java泛型:泛型仅定义为返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找GWT的一些GXT代码,并且我碰到了这种泛型的使用,我无法在Java教程中找到另一个示例。类名是,如果你想看看所有的代码。这里有一些重要的部分:

I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is com.extjs.gxt.ui.client.data.BaseModelData if you want to look at all of the code. Here are the important parts:

private RpcMap map;

public <X> X get(String property) {
  if (allowNestedValues && NestedModelUtil.isNestedProperty(property)) {
    return (X)NestedModelUtil.getNestedValue(this, property);
  }
  return map == null ? null : (X) map.get(property);
}

X 已定义无处不在类或层次结构中的任何地方,并且当我在eclipse中点击去声明时,它只会进入公共方法签名中的< X>

X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the <X> in the public method signature.

我试着用以下两个例子调用这个方法来看看会发生什么:

I've tried to call this method with the following two examples to see what happens:

public Date getExpiredate() {
    return  get("expiredate");
}

public String getSubject() {
    return  get("subject");
}

它们编译并显示没有错误或警告。至少我会认为我必须做一个演员才能使这个工作。

They compile and show no errors or warnings. I would think at the very least I would have to do a cast to get this to work.

这是否意味着泛型允许一个神奇的返回值,可以是任何东西会在运行时炸毁吗?这似乎与仿制药应该做什么相反。任何人都可以向我解释这一点,并可能给我一个链接到一些文件,解释这个更好一点?我已经浏览了Sun的23页关于泛型的pdf,并且返回值的每个示例都是在类级别定义的,或者是在传入的其中一个参数中定义的。

Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime? This seems counter to what generics are supposed to do. Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better? I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.

推荐答案

该方法返回您期望的类型(< X> 在方法中定义并且绝对无界)

The method returns a type of whatever you expect it to be (<X> is defined in the method and is absolutely unbounded).

这是非常非常危险的,因为没有规定返回类型实际上与返回值相匹配。

This is very, very dangerous as no provision is made that the return type actually matches the returned value.

这样做的唯一好处是,您不必强制转换返回任何类型的通用查找方法的返回值。

The only advantage this has is that you don't have to cast the return value of such generic lookup methods that can return any type.

我会说:小心使用这样的构造,因为你几乎失去了所有的类型安全,并且只有在每次调用 get()时不必写明确的转换。

I'd say: use such constructs with care, because you lose pretty much all type-safety and gain only that you don't have to write an explicit cast at each call to get().

是的:这几乎是在运行时爆发出来的黑魔法,并打破了泛型应该实现的全部想法。

And yes: this pretty much is black magic that blows up at runtime and breaks the entire idea of what generics should achieve.

这篇关于Java泛型:泛型仅定义为返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:44