在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) 我发现你可以使用特殊类型调用泛型方法,例如:
假设我们有一个通用的方法:
class ListUtils {
public static <T> List<T> createList() {
return new ArrayList<T>();
}
}
Run Code Online (Sandbox Code Playgroud)
我们可以称之为:
List<Integer> intList = ListUtils.<Integer>createList();
Run Code Online (Sandbox Code Playgroud)
但是,当它静态导入时我们怎么称它呢?例如:
List<Integer> intList = <Integer>createList();
Run Code Online (Sandbox Code Playgroud)
这不起作用.
这是什么意思?
HashBiMap<Character, Integer> charOcc = HashBiMap.<Character, Integer> create();
Run Code Online (Sandbox Code Playgroud) 这段代码似乎工作正常
class Rule<T>
{
public <T>Rule(T t)
{
}
public <T> void Foo(T t)
{
}
}
Run Code Online (Sandbox Code Playgroud)
例
Rule<String> r = new Rule<String>();
Run Code Online (Sandbox Code Playgroud)
这通常适用于类的类型参数,在它们不冲突的情况下吗?我的意思是当只有类有一个类型参数,而不是构造函数,或者这是否在构造函数中查找类型参数?如果他们发生冲突,这会如何变化?
请参阅下面的讨论
如果我有一个函数调用
x = <Type Parameter>method(); // this is a syntax error even inside the function or class ; I must place a this before it, why is this, and does everything still hold true. Why don't I need to prefix anything for the constructor call. Shouldn't Oracle …Run Code Online (Sandbox Code Playgroud)