Java - 泛型与Casting对象 [英] Java - Generics vs Casting Objects

查看:203
本文介绍了Java - 泛型与Casting对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类数据< T>

b

private T value;

有更好的方法来执行以下操作吗?

ie返回通用类型以不同的形式?

is there nicer way to do the following?
ie returning the generic type in different forms?

public List<String> getValues() {
    if (value.getClass() != ArrayList.class)
        throw new Exception("Wrong Enum value '%s'", value);
    return (ArrayList<String>) value;
    //ugly
}


public String getStringValue() {
    if (value.getClass() != String.class)
        throw new Exception("Wrong value type '%s'", value);
    return (String) value;
    //ugly
}

public Float getFloatValue() {
    if (value.getClass() != Double.class)
        throw new Exception("Wrong value type '%s'", value);
    return (Float) value;
    //ugly
}

public Long getLongValue() {
    if (value.getClass() != Double.class)
        throw new Exception("Wrong value type '%s'", value);
    return (Long) value;
    //ugly
}
public T getValue() {
    return value;
}

精确,我使用Gson作为解串器,数据对象可以是异构的

也可以注册适配器用于浮动和长检测,但不会更快或更好

Precision, I'm using Gson as deserializer, to get a List, each Data objects can then be heterogeous
Could also register adapters for float and long detection, but it wouldn't be faster or nicer

编辑:gson无法检索long:

edit: gson fails to retrieve longs:

 ((Long) d.getValue())

java.lang.Double到java.lang.Long

java.lang.Double cannot be cast to java.lang.Long

Long.parseLong( d.getValue().toString())

java.lang.NumberFormatException: 212231.0

java.lang.NumberFormatException: For input string: "212231.0"

我尝试注册LongAdpater

I tried to register a LongAdpater

gsonBuilder.registerTypeAdapter(Long.class, new LongAdapter());

private static class LongAdapter implements 
    JsonSerializer<Long>, JsonDeserializer<Long> 
{

    @Override public Long deserialize(
            JsonElement json, 
            Type type,
            JsonDeserializationContext arg2) throws JsonParseException 
    {
        return json.getAsLong();
    }

    @Override
    public JsonElement serialize(Long l, Type arg1,
            JsonSerializationContext arg2) {
        return new JsonPrimitive(new Double(l));
    }
}

java.lang.IllegalArgumentException:无法注册类型适配器java.lang.Long类别

java.lang.IllegalArgumentException: Cannot register type adapters for class java.lang.Long

edit2

Data<Float> d1 = new Data<Float>( new Float(6.32));
List<String> l = new ArrayList<String>();
    l.add("fr");
    l.add("it");
    l.add("en");
Data<List<String>> d2 = new Data<List<String>>( l);
Data<Long> d3 = new Data<Long>(new Long(212231));

List<Data> data = new ArrayList<Data>();
    data.add(d1);
    data.add(d2);
    data.add(d3)

new Gson().toJson(data);


推荐答案

strong>允许类同时使用不同类型。

The point of generics is NOT to allow a class to use different types at the same time.

泛型允许您定义/限制 em 。

Generics allow you to define/restrict the type used by an instance of an object.

泛型的思想是消除需要强制转换。

The idea behind generics is to eliminate the need to cast.

使用泛型与您的类应该导致这样的东西:

Using generics with your class should result in something like this:

Data<String> stringData = new Data<String>();
String someString = stringData.getValue();

Data<Long> longData = new Data<Long>();
Long someLong = longData.getValue();

Data<List<String>> listData = new Data<List<String>>();
List<String> someList = listData.getValue();

您应该使用对象 / strong> - 使用泛型避免投射。

You should either use Objects and casting --OR-- use generics to avoid casting.

你似乎相信泛型允许在同一个实例中进行异类打字。

You seem to believe that generics allow for heterogeneous typing within the same instance.

这不正确。

如果你想让列表包含一系列混合类型,不合适。

If you want a list to contain a mixed bag of types, then generics are not appropriate.

此外...

使用 Double.longValue( )

要从double创建浮动,请使用 Double.floatValue()

To create a float from a double, use Double.floatValue().

我建议您阅读文档

这篇关于Java - 泛型与Casting对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆