消除java泛型的类型参数 [英] Eliminate type parameter of java generics

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

问题描述

代码:

  interface属性< T> 
{
T get();
}

类BoolProperty实现Property< Boolean>
{
@Override
public Boolean get()
{
return false;
}
}
class StringProperty implements Property< String>
{
@Override
public String get()
{
returnhello;
}
}
类OtherStringProperty实现Property< String>
{
@Override
public String get()
{
returnbye;

public String getSpecialValue()
{
returnyou special;


$ / code $ / pre

由我的课程使用:

  class结果< P extends Property< X>,X> 
{
P p;
列表< X>列表;

$ / code>

正如你看到它有两个类型参数 P X 。尽管 X 总是可以从 P 推断出来,但是语言要求我提供两种:

 结果< BooleanProperty,Boolean> res = new Result< BooleanProperty,Boolean>(); 

是否有任何技巧可以摆脱 X 类型参数?我只想使用

 结果<布尔属性> res = new Result< BooleanProperty>(); 

另外,我不想丢失类型信息并将其用作:

 结果< OtherStringProperty> res = new Result< OtherStringProperty>(); 
String spec = res.p.getSpecialValue();
String prop = res.list.get(0);


解决方案

有一个类似的问题, :https://stackoverflow.com/a/4452268/247763



基本上,没有真正的方法来解决包括额外的泛型类型,因为如果没有它,编译器无法知道你使用的是什么类型。我猜这会影响你的方法的目的,但你可以在指定类型的时候尝试扩展 Result ,例如:

  class BoolResult extends Result< BoolProperty,Boolean> {
//做东西
}


The code:

interface Property<T>
{
    T get();
}

class BoolProperty implements Property<Boolean>
{
    @Override
    public Boolean get()
    {
        return false;
    }
}
class StringProperty implements Property<String>
{
    @Override
    public String get()
    {
        return "hello";
    }
}
class OtherStringProperty implements Property<String>
{
    @Override
    public String get()
    {
        return "bye";
    }
    public String getSpecialValue()
    {
        return "you are special";
    }
}

is used by my class:

class Result<P extends Property<X>, X>
{
    P p;
    List<X> list;
}

As you see it has two type parameters P and X. Despite of that the X can always be deduced from P but the language requires me to supply both:

Result<BooleanProperty, Boolean> res = new Result<BooleanProperty, Boolean>();

Is there any trick to get rid of the X type parameter? I want just use

Result<BooleanProperty> res = new Result<BooleanProperty>();

Also, I don't want lose type information and use it as:

Result<OtherStringProperty> res = new Result<OtherStringProperty>();
String spec = res.p.getSpecialValue();
String prop = res.list.get(0);

解决方案

There is a similar question whose answer you might find interesting: https://stackoverflow.com/a/4452268/247763

Essentially, there's no real way to get around including the extra generic type, because the compiler can't know what type you're using without it. I'm guessing this defeats the purpose of your approach, but you could try extending Result while specifying the types - something like this:

class BoolResult extends Result<BoolProperty, Boolean> {
    // Do stuff
}

这篇关于消除java泛型的类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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