在C#中我可以这样做:
//This is C#
static T SomeMethod<T>() where T:new()
{
Console.WriteLine("Typeof T: "+typeof(T));
return new T();
}
//And call the method here
SomeMethod<SomeClassName>();
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,我不能让它在Java中工作.
我想要做的是,在超类上创建一个静态方法,这样子类就可以转换为XML.
//This is Java, but doesn't work
public static T fromXml<T>(String xml) {
try {
JAXBContext context = JAXBContext.newInstance(T.class);
Unmarshaller um = context.createUnmarshaller();
return (T)um.unmarshal(new StringReader(xml));
} catch (JAXBException je) {
throw new RuntimeException("Error interpreting XML response", je);
}
}
//Also the call doesn't work...
fromXml<SomeSubObject>("<xml/>");
Run Code Online (Sandbox Code Playgroud) 一位同事检查了这段代码:
Number n = ...;
double nr = n == null ? 0.0 : (double) n;
Run Code Online (Sandbox Code Playgroud)
然后另一位同事抱怨说这没有编译,这就是我所期待的.然而,事实证明我已经从SVN中提取了这些代码并且一切正常.我们都在eclipse中将Java版本设置为1.7,结果证明代码在eclipse 4.4.2(Luna)下编译得很好但在4.2.2下失败了.
我通过替换演员来解决问题n.doubleValue()
.
现在的实际问题是:为什么这首先被接受了?它当然应该工作的铸造时Double
的代替double
,但我认为,从直接投Number
给double
被判无效.那么,这是eclipse 4.2.2中的一个错误,在此期间修复了,或者eclipse 4.4.2是否默默接受不应该编译的代码(恕我直言,这将是一个错误)?
作为Eclipse中的Java泛型编译的后续编译,但不是在javac中,我发布了另一个在Eclipse中编译并运行良好的代码片段,但在javac中引发了编译错误.(这可以防止从Maven构建提取代码段的项目.)
自包含的代码段:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<Foo<?>> setOfFoos = new HashSet<Foo<?>>();
List<Foo<?>> sortedListOfFoos = asSortedList(setOfFoos);
}
public static <T extends Comparable<T>> List<T> asSortedList(Collection<T> c) {
List<T> list = new ArrayList<T>(c);
java.util.Collections.sort(list);
return list;
}
public static class Foo<T> implements Comparable<Foo<T>> {
@Override
public int compareTo(Foo<T> o) {
return 0;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在javac中编译返回:
Main.java:11: <T>asSortedList(java.util.Collection<T>) in Main cannot be applied …
Run Code Online (Sandbox Code Playgroud)