如何找到子类的方法?

问题描述 投票:0回答:1

我正在构建一些类,这些类将表示要转换为JSON的数据。

这些字段的值可以是各种类型(可能是整数,可能是布尔值。)

这是到目前为止我所拥有的一个示例(最小的可复制示例):

import javax.json.Json;
import javax.json.JsonObjectBuilder;

abstract class AttributeValue {}

class AttributeValueInt extends AttributeValue {
    private int value;

    AttributeValueInt( int value ) {this.value = value;}

    int getValue() { return value; }
}

class AttributeValueBool extends AttributeValue {
    private boolean value;

    AttributeValueBool( boolean value ) {this.value = value;}

    boolean getValue() { return value; }
}

class Attribute {
    private AttributeValue attrValue;

    Attribute( AttributeValue attrValue ) { this.attrValue = attrValue; }

    AttributeValue getAttrValue() { return attrValue; }
}

class Example {
    void getJSON( Attribute attribute ) {
        JsonObjectBuilder builder = Json.createObjectBuilder();
        builder.add( "key", attribute.getAttrValue().getValue() );
        // Cannot resolve method 'getValue()'
    }
}

AttributeValueIntAttributeValueBool扩展了抽象类AttributeValuevalue(朝下)可以是AttributeValueInt或AttributeValueBool。

由于这两个类都实现了getValue方法,所以我希望attribute.getAttrValue().getValue()可以相应地解析为int或boolean。

完整错误是这样:

Error:(39, 61) java: cannot find symbol
  symbol:   method getValue()
  location: class com.fanduel.brazepublishing.AttributeValue

我如何使它正常工作?我曾考虑向抽象类中添加抽象getValue方法,但是其返回类型是什么?

java class java-8 abstract-class
1个回答
0
投票

您可以为此使用通用名称。这里是一个例子:

abstract class AttributeValue<AttributeType> {
    AttributeType value;

    AttributeType getValue() {
        return value;
    }
}


class AttributeValueInt extends AttributeValue<Integer> {
    AttributeValueInt(int value) {
        this.value = value;
    }
}


class AttributeValueBool extends AttributeValue<Boolean> {
    AttributeValueBool(boolean value) {
        this.value = value;
    }
}


class Main {


    static String getJson(AttributeValue<?> attribute) {
        return "key: " + attribute.getValue();
    } 


    public static void main(String[] args) {
        AttributeValue<?> attributeInt = new AttributeValueInt(42);
        AttributeValue<?> attributeBool = new AttributeValueBool(true);

        System.out.println(getJson(attributeInt));
        System.out.println(getJson(attributeBool));
    }
}

在这里您可以在getValue实例上调用AttributeValue,因为属性的类型由<AttributeType>指定。一个缺点是您不能再使用基本类型。

© www.soinside.com 2019 - 2024. All rights reserved.