相关疑难解决方法(0)

Java中没有泛型参数的通用方法

在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)

java generics

35
推荐指数
3
解决办法
5万
查看次数

当静态导入时,如何使用类型调用Generic方法?

我发现你可以使用特殊类型调用泛型方法,例如:

假设我们有一个通用的方法:

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)

这不起作用.

java generics static-import

13
推荐指数
1
解决办法
2676
查看次数

奇怪的Java通用

这是什么意思?

HashBiMap<Character, Integer> charOcc = HashBiMap.<Character, Integer> create();
Run Code Online (Sandbox Code Playgroud)

java generics

6
推荐指数
2
解决办法
1041
查看次数

泛型Java和类型参数的阴影

这段代码似乎工作正常

class Rule<T>
{

    public <T>Rule(T t)
    {

    }
    public <T> void Foo(T t)
    {

    }
 }
Run Code Online (Sandbox Code Playgroud)
  1. 方法类型参数是否影响类类型参数?
  2. 另外,当你创建一个对象时,它是否使用类的类型参数?

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)

java generics

6
推荐指数
1
解决办法
628
查看次数

标签 统计

generics ×4

java ×4

static-import ×1