简体   繁体   English

如何确定Java中通用方法的类型?

[英]How to determine type in a generic method in Java?

I want a method that extracts the data from a JSON-object parsed before as the correct type. 我想要一个从正确解析的JSON对象中提取数据的方法。 The JSONObject (rawdata) extends Map, so it looks like this: JSONObject(rawdata)扩展了Map,因此如下所示:

private <Type> Type getValue(String key, Type def)
{
    if (!rawdata.containsKey(key)) return def;
    if (!(rawdata.get(key) instanceof Type)) return def;
    return (Type) rawdata.get(key);
}

The instanceof obviously generates a compile-time-error. instanceof显然会产生一个编译时错误。 The parameter def is the default-value, returned if the key is not available or has the wrong type. 参数def是默认值,如果键不可用或类型错误,则返回该值。 But def can also be null, so def.getClass() isn't working. 但是def也可以为null,因此def.getClass()无法正常工作。

Any ideas how I can check the content of the Map-entry for the correct type? 有什么想法可以检查Map-entry内容的正确类型吗?

由于类型擦除,处理默认值可以为null的情况的唯一方法是让该方法需要一个额外的Class类型的参数-通常更好,因为它允许默认值成为所需类型的子类。

You just need to check for nulls (a null will count as any type, if this is undesired behaviour then you will also need to pass in the desired class). 您只需要检查null(null将被视为任何类型,如果这是不希望的行为,那么您还需要传递所需的类)。

private <T> T getValue(String key, T def)
{
    if (!rawdata.containsKey(key)) return def;

    Object value = rawdata.get(key);

    if (def == null) return (T) value; 
    // note that the above is inherently unsafe as we cannot 
    // guarantee that value is of type T

    // this if statement is the same as "value instanceOf Type"
    // is type safe, but not null safe
    if (def.getClass().isAssignableFrom(value.getClass())) {
        return (T) value;
    } else {
        return def;
    }
}

A safer method signature would be: 一个更安全的方法签名是:

private <T> T getValue(String key, T defaultValue, Class<T> defaultClass)

This way we can safely check the types match even when the default is null. 这样,即使默认值为null,我们也可以安全地检查类型是否匹配。

Your best bet is probably to accept a Class object for the return type in the case when no default value is given. 在没有给出默认值的情况下,最好的选择是接受Class对象作为返回类型。 You can just overload the function like: 您可以像这样重载函数:

private <T> T getValue(String key, Type defaultValue);

private <T> T getValue(String key, Class<T> type);

Or you could use the Typesafe Heterogeneous Container (THC) pattern from "Effective Java Second Edition" book by Joshua Bloch. 或者,您可以使用Joshua Bloch撰写的“ Effective Java Second Edition”一书中的Typesafe异构容器 (THC)模式。

Basically, store the item's Class in the map when inserting. 基本上,插入时将商品的Class存储在地图中。 When retrieving you'll know the type is the same. 检索时,您会知道类型相同。

Map<Class, Map<String, Object>> rawData = ...

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

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