简体   繁体   English

Java泛型:如何指定确切的方法签名

[英]Java generics: How to specify exact method signature

I have a class with various constructors: 我有一个带有各种构造函数的类:

public class SomeClass {

    public SomeClass(Object obj) {
        Log.d("x", "SomeClass(Object)");
    }

    public SomeClass(Integer num) {
        Log.d("x", "SomeClass(Integer)");
    }

    public SomeClass(String str) {
        Log.d("x", "SomeClass(String)");
    }

    public <K, V> SomeClass(Map<K, V> map) {
        Log.d("x", "SomeClass(List)");
        for (K key : map.keySet()) {
            new SomeClass(key);
            new SomeClass(map.get(key));
        }
    }
}

...and some code which uses it in following way: ...以及一些通过以下方式使用它的代码:

HashMap<String, Integer> map = new HashMap<>();
map.put("key", 100);
new SomeClass(map);

In the result I have such output: 结果是这样的输出:

"SomeClass(List)"
"SomeClass(Object)"
"SomeClass(Object)"

instead of required 而不是必需的

"SomeClass(List)"
"SomeClass(String)"
"SomeClass(Integer)"

I suppose that because of Java Type Erasure the nested calls of SomeClass constructors falls to the most general one. 我想由于Java Type Erasure,SomeClass构造函数的嵌套调用属于最普通的构造函数。

The Question: any ideas how to overcome this Java behavior and force it to call constructor with required parameter type? 问题:关于如何克服这种Java行为并强制其以必需的参数类型调用构造函数的想法? (Static wrappers and Fabric pattern is not accepted here) (此处不接受静态包装器和Fabric模式)

Overload is done at compile time and therefore uses the static type of a variable rather than the runtime type. 重载在编译时完成,因此使用变量的静态类型而不是运行时类型。 This is nothing to do with generics. 这与泛型无关。

Consider the code: 考虑代码:

Object value = "value";
SomeClass something = new SomeClass(value);

Then the SomeClass(Object) overload is used. 然后使用SomeClass(Object)重载。

You could use instanceof , but that's usually a good indication that there is something wrong in the design. 您可以使用instanceof ,但这通常可以很好地表明设计中存在问题。 Almost certainly you want the Map to have a relevant type. 几乎可以肯定,您希望Map具有相关的类型。 At the moment you could write the last constructor as: 目前,您可以将最后一个构造函数编写为:

public SomeClass(Map<?, ?> map) {

(BTW, generic constructors are really obscure.) (顺便说一句,通用构造函数确实很晦涩。)

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

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