简体   繁体   English

从通用抽象类Java返回子类

[英]Return subclass from generic abstract class java

So, I have this abstract class that represents an Input type object - 因此,我有一个抽象类,代表一个Input类型的对象-

public abstract class Input<E>

And I have two classes that extends it, one is ButtonInput and the other is TextInput. 我有两个扩展它的类,一个是ButtonInput,另一个是TextInput。 Both extend Input so it doesn't really matter. 两者都扩展了Input,所以实际上并不重要。 I'll use TextInput just to explain. 我将使用TextInput进行解释。
This is the TextInput class defention: 这是TextInput类的防护:

public class TextInput extends Input<TextInput>

What I'm trying to do is to return this as E (TextInput in this case)- 我试图做的是(在这种情况下的TextInput)返回为E -

public E setTextColor(Color color) {
        this.colorText = color;
        return (E)this;
    }

So, If I call for example: 因此,如果我举个例子:

new TextInput().setColor(Color.black)

It should return TextInput. 它应该返回TextInput。 It is working but, it shows the following warning - 它正在工作,但是显示以下警告-

warning: [unchecked] unchecked cast 警告:[未选中]未选中的演员表
return (E) this; 返回(E)这个; required: E 必填:E
found: Input 找到:输入
where E is a type-variable: 其中E是类型变量:
E extends Object declared in class Input E扩展在Input类中声明的Object

In relation to the following line of code - 关于以下代码行-

 return (E) this;

Does anybody knows how to solve it? 有人知道如何解决吗?
Thanks 谢谢

This is a pattern I've used in the past to solve this type of issue in abstract builder patterns. 这是我过去用来解决抽象生成器模式中此类问题的一种模式。 It relies on an abstract me() method that is overridden to return a reference to the concrete object. 它依赖于抽象的me()方法,该方法被重写以返回对具体对象的引用。

abstract class Foo<T> {
    protected abstract T me();

    public T baz() {
        return me();
    }
}

class Bar extends Foo<Bar> {
    protected Bar me() {
        return this;
    }
}

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

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