- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
如果在Java中创建一个泛型类(该类有泛型类型参数),可以使用泛型方法(该方法接受泛型类型参数)吗?
考虑以下示例:
public class MyClass {
public <K> K doSomething(K k){
return k;
}
}
public class MyGenericClass<T> {
public <K> K doSomething(K k){
return k;
}
public <K> List<K> makeSingletonList(K k){
return Collections.singletonList(k);
}
}
正如您对泛型方法所期望的那样,我可以调用 doSomething(K)
在 MyClass
的实例上与任何对象:
MyClass clazz = new MyClass();
String string = clazz.doSomething("String");
Integer integer = clazz.doSomething(1);
但是,如果我尝试使用 MyGenericClass
的实例没有指定泛型,我调用 doSomething(K)
返回 Object
,不管是什么K
传入:
MyGenericClass untyped = new MyGenericClass();
// this doesn't compile - "Incompatible types. Required: String, Found: Object"
String string = untyped.doSomething("String");
奇怪的是,如果返回类型是泛型类,它将编译 - 例如。 List<K>
(实际上,这可以解释 - 请参阅下面的答案):
MyGenericClass untyped = new MyGenericClass();
List<String> list = untyped.makeSingletonList("String"); // this compiles
此外,如果泛型类被键入,即使只使用通配符,它也会编译:
MyGenericClass<?> wildcard = new MyGenericClass();
String string = wildcard.doSomething("String"); // this compiles
为什么在非类型化泛型类中调用泛型方法不起作用有充分的理由吗?
我是否缺少一些与泛型类和泛型方法相关的巧妙技巧?
编辑:
为了澄清,我希望无类型或原始类型的泛型类不尊重泛型类的类型参数(因为它们尚未提供)。但是,我不清楚为什么无类型或原始类型的泛型类意味着泛型方法不被尊重。
事实证明,这个问题已经在 SO 上提出,c.f. this question .对此的答案解释说,当一个类是无类型的/以其原始形式时,所有泛型从该类中删除 - 包括泛型方法的类型。
但是,对于为什么会这样,并没有真正的解释。所以请允许我澄清一下我的问题:
编辑 - JLS 的讨论:
已建议(在回答上一个 SO 问题和此问题时)在 JLS 4.8 中处理此问题,其中指出:
The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.
我很清楚这与非类型化类有何关系——类泛型类型被删除类型替换。如果类泛型已绑定(bind),则删除类型对应于这些边界。如果它们未绑定(bind),则删除类型为 Object - 例如
// unbound class types
public class MyGenericClass<T> {
public T doSomething(T t) { return t; }
}
MyGenericClass untyped = new MyGenericClass();
Object t = untyped.doSomething("String");
// bound class types
public class MyBoundedGenericClass<T extends Number> {
public T doSomething(T t) { return t; }
}
MyBoundedGenericClass bounded = new MyBoundedGenericClass();
Object t1 = bounded.doSomething("String"); // does not compile
Number t2 = bounded.doSomething(1); // does compile
虽然泛型方法是实例方法,但我不清楚 JLS 4.8 是否适用于泛型方法。泛型方法的类型(在前面的示例中为 <K>
)不是无类型的,因为它的类型由方法参数确定 - 只有类是无类型/原始类型的。
最佳答案
'为了向后兼容'似乎是删除类泛型类型的充分理由——它是必需的,例如允许您返回一个无类型列表并将其传递给一些遗留代码。将此扩展到泛型方法似乎是一个棘手的子案例。
4.8 中的 JLS 片段(您引用)涵盖了构造函数、实例方法和成员字段 - 泛型方法通常只是实例方法的一个特例。因此,此代码段似乎涵盖了您的情况。
使 JLS 4.8 适应这种特定情况:
The type of a generic method is the raw type that corresponds to theerasure of its type in the generic declaration corresponding to C.
(这里方法的“类型”将包括所有参数和返回类型)。如果您将“删除”解释为“删除所有泛型”,那么这似乎与观察到的行为相匹配,尽管它不是很直观甚至没有用。删除所有泛型,而不仅仅是泛型类参数,这似乎是一种过分热心的一致性(尽管我是谁来猜测设计者)。
类泛型参数与方法泛型参数交互时可能会出现问题 - 在您的代码中,它们是完全独立的,但您可以想象将它们分配/混合在一起的其他情况。我认为值得指出的是,根据 JLS,不建议使用原始类型:
The use of raw types is allowed only as a concession to compatibilityof legacy code. The use of raw types in code written after theintroduction of genericity into the Java programming language isstrongly discouraged. It is possible that future versions of the Javaprogramming language will disallow the use of raw types
Java 开发人员的一些想法在这里很明显:
http://bugs.sun.com/view_bug.do?bug_id=6400189
(错误 + 修复显示方法的返回类型被视为方法类型的一部分,以便进行这种类型删除)
还有this request ,其中有人似乎要求您描述的行为 - 只删除类泛型参数,而不是其他泛型 - 但它被以下理由拒绝:
The request is to modify type erasure so that in the type declaration
Foo<T>
, erasure only removesT
from parameterized types. Then, it so happens that withinMap<K,V>
's declaration,Set<Map.Entry<K,V>>
erases toSet<Map.Entry>
.But if
Map<K,V>
had a method that took typeMap<String,V>
, its erasure would just beMap<String>
. For type erasure to change the number of type parameters is horrific, especially for compile-time method resolution. We are absolutely not going to accept this request.It is too much to expect to be able to use raw types (
Map
) while still getting some of the type-safety of generics (Set<Map.Entry>
).
关于泛型类中的 Java 泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18001550/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!