严重的泛型问题:int vs. Integer java [英] Serious generics issue: int vs. Integer java

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

问题描述

很长一段时间,我一直试图让一段代码工作,但这是不可能的。我所要求的类需要一个我设置为Integer的泛型。所以我尝试了以下内容:

for a long while, i have been trying to get a piece of code to work, and it just is not possible. the class i have requires a generic which i have set to Integer. so i tried the follwoing:

public class a<T> //set generics for this function
{
    private T A;
    protected boolean d;

    public a(final T A)
    {
        this.A = A;

        //do calculations
        //since constructor cannot return a value, pass to another function.
        this.d = retnData(Integer.parseInt(A.toString()) != 100); //convert to an integer, the backwards way.
    }
    private boolean retnData(boolean test)
    {
        return test;
    }
}
// IN ANOTHER CLASS
transient a<Integer> b;
boolean c = b.d = b.a(25); // throws an erorr: (Int) is not apporpriate for a<Integer>.a

Java将不允许这样,因为java看到int!= Integer,即使两者都接受相同的数据。并且由于仿制药的工作方式,我无法设置b;因为int类型的原始性。即使转换为整数也不起作用,因为它仍然会抛出类型错误

Java will not allow this since java sees that int != Integer, even though both accept the same data. and because of the way generics works i cannot set a b; because of the primitiveness of the type int. Even casting to an Integer does not work, as it still throws the "type error"

finnaly,我不得不问是否有某种解决方法,或尝试让它工作是徒劳的吗?

finnaly, i have to ask if there is some sort of work around for this, or is it futile to try and get this to work?

推荐答案

您正试图显式调用构造函数作为实例方法。这不能用Java完成。

You are trying to explicitly call a constructor as an instance method. This cannot be done in Java.

也许你想要:

transient a<Integer> b = new a<Integer>(25);
boolean c = b.d;

但是,因为 d 被宣布为 protected ,仅当此代码位于从 a 派生的另一个类或同一个包中时才有效。

However, since d is declared to be protected, that will only work if this code is in another class derived from a or in the same package.

这篇关于严重的泛型问题:int vs. Integer java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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