Matt
Matt

Reputation: 2843

Java - Return type of generic type

Im new ish to Generics in Java but how can a return type be compiled at runtime, is this possible? I have a class that acts as a decorator over an entity, if the entity property is "mapped", then a different value is returned, however the value from the property of the entity can be any type.

My code is as follows: Obviously GENERIC_TYPE is the type i want to know or can be a wildcard


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
    }
}

Upvotes: 2

Views: 91

Answers (1)

Jorn Vernee
Jorn Vernee

Reputation: 33905

Another design, besides generic, would be a wrapper around MyEntity that sometimes delegates, and sometimes does something else.

First you need to declare an Entity interface, that MyEntity implements:

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

class MyEntity implements Entity {...}

Then you can create decorators using anonymous classes:

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
        }
    };
}

Then use it like:

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

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

Upvotes: 1

Related Questions