Choose what interface to implement at runtime

≡放荡痞女 提交于 2020-01-05 04:10:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/43901624/choose-what-interface-to-implement-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!