繁体   English   中英

Java - 泛型类型的返回类型

[英]Java - Return type of generic type

我是 Java 泛型的新手,但是如何在运行时编译返回类型,这可能吗? 我有一个类充当实体的装饰器,如果实体属性被“映射”,则返回一个不同的值,但是实体属性的值可以是任何类型。

我的代码如下:显然 GENERIC_TYPE 是我想知道的类型或者可以是通配符


package com.example;

public final class ObjectPropertyGetter
{
    private final Map mappings;

    public ObjectPropertyGetter(Map<String, GENERIC_TYPE> mappings)
    {
        this.mappings = mappings;
    }

    public GENERIC_TYPE getValueFor(Object entity, String property)
    {
        GENERIC_TYPE valueOfProperty = getValueOfProperty(property); // left out for simplicity

        if (mappings.containsKey(property)) {
            return mappings.get(property);
        }

        return valueOfProperty;
    }

    public class MyEntity{
        public String foo;
        public Integer bar;
    }

    public static void main(String[] args)
    {
        Map<String, GENERIC_TYPE> mappings = new HashMap();
        mappings.put("bar", 3);

        MyEntity entity = new MyEntity();
        entity.foo = "a";
        entity.bar = 2;

        ObjectPropertyGetter propGetter = new ObjectPropertyGetter(mappings);

        String foo = propGetter.getValueFor(entity, "foo"); // equals "a"
        Integer bar = propGetter.getValueFor(entity, "bar"); // equal 3
    }
}

除了通用之外,另一种设计是围绕MyEntity的包装器,它有时委托,有时做其他事情。

首先你需要声明一个Entity接口, MyEntity实现:

interface Entity {
    String getFoo();
    int getBar();
}

class MyEntity implements Entity {...}

然后你可以使用匿名类创建装饰器:

public static Entity mapBar(Entity toWrap, int newBar) {
    return new Entity() {
        @Override
        public String getFoo() {
            return toWrap.getFoo(); // delegate
        }

        @Override
        public int getBar() {
            return newBar; // return another value
        }
    };
}

然后像这样使用它:

Entity ent = new MyEntity();
ent = mapBar(ent, 3);

String foo = ent.getFoo(); // "a"
int bar = ent.getBar(); // 3

暂无
暂无

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

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