alexsius
alexsius

Reputation: 43

Choose what interface to implement at runtime

I'm wondering if, in Java, there is a way to create an object from a class implementing multiple interfaces, but choosing at runtime what interfaces should be implemented. Those interfaces would have no methods, this would be a way to create an object by defining at run time which attributes should have. That is my real problem. USE CASE: I have a class with a huge number of attributes but the objects created from this class would use only some of those attributes, some will be in common between objects some not, what attributes should be used is decided at runtime by the user. I want to avoid to create objects with a lot of empty attributes.

Upvotes: 1

Views: 467

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

Maybe a Proxy class might be interesting.

I would consider testing capabilities/features:

interface Flying { void fly(); }
interface Swimming { void swim(); }

Animal animal = ...

Optional<Flying> flying = animal.lookup(Flying.class);
flying.ifPresent(f -> f.fly());    interface Flying { void fly(); }


Optional<Swimming> swimming = animal.lookup(Swimming.class);
swimming.ifPresent(sw -> sw.swim());

Animal need not implement any interface, but you can look up (lookup or maybe as) capabilities. This is extendible in the future, dynamic: can change at run-time.

Implementation as

private Map<Class<?>, ?> map = new HashMap<>();

public <T> Optional<T> lookup(Class<T> type) {
     Object instance = map.get(type);
     if (instance == null) {
         return Optional.empty();
     }
     return Optional.of(type.cast(instance));
}

<S> void register(Class<S> type, S instance) {
    map.put(type, instance);
}

The implementation does a safe dynamic cast, as register ensures the safe filling of (key, value) entries.

Upvotes: 1

Related Questions