简体   繁体   English

Java泛型类型推断

[英]Java generic type inference

I am trying to pass 我试图通过

Map<String, Map<String, List<TranslationImport>>> variable

to super class's constructor that expects: 到预期的超类的构造函数:

Map<String, Map<String, List>>  

I tried changing parent class's constructor to expect 我尝试更改父类的构造函数以期望

Map<String, Map<String, List<?>>> 

and

Map<String, Map<String, ? extends List>> 

to no avail. 无济于事。

If I understand correctly, you can change the superclass constructor signature; 如果我理解正确,则可以更改超类构造函数签名。 you just need something that accepts an arbitrary value for the List element type? 您只需要一些可以接受List元素类型的任意值的东西?

That should probably be Map<String, ? extends Map<String, ? extends List<?>>> 那应该是Map<String, ? extends Map<String, ? extends List<?>>> Map<String, ? extends Map<String, ? extends List<?>>> Map<String, ? extends Map<String, ? extends List<?>>> . Map<String, ? extends Map<String, ? extends List<?>>>

Maybe this will "help" a litle 也许这会“帮助”一小撮

static void test(Map<String, Map<String, List>> m) {
    System.out.println(m);
}
public static void main(String[] args) {
    Map<String, Map<String, List<TranslationImport>>> variable = new HashMap<String, Map<String, List<TranslationImport>>>();
    Map<String, Map<String, List>> m2=(Map)variable;
    test(m2);
}

the problem is that capture conversion is not applied recursively: 问题是捕获转换不是递归应用的:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.10 http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.10

so '?' 所以'?' within nested < > is ignored for capture conversion 嵌套<>中的内容将被捕获转换忽略

one way (although not completely satisfactory from the point of view of getting any value from generics) to make your code work would be to do something like: 一种使代码正常工作的方法(尽管从从泛型中获取任何价值的观点来看并不完全令人满意)是执行以下操作:

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

public class Foo extends FooParent {
    Foo(Map<String, Map<String, List<TranslationImport>>> variable) {
        super(variable);
        System.out.println("ok");
    }
    public static void main(String[] args) {
        Map<String, Map<String, List<TranslationImport>>> var =
            new HashMap<String, Map<String, List<TranslationImport>>>();
        Foo foo = new Foo(var);
    }
}

class FooParent {
    FooParent(Map<String, ?> variable) {
        System.out.println("FooParent constructor");
    }
}

class TranslationImport {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM