本文介绍了选择要在运行时实现的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Java中是否有一种方法可以从实现多个接口的类中创建一个对象,但是在运行时选择应该实现哪些接口.这些接口将没有方法,这将是通过在运行时定义应具有哪些属性来创建对象的方法.那是我真正的问题.用例:我有一类具有大量属性的类,但是从此类创建的对象将仅使用这些属性中的一些,一些将在对象之间相同,有些则不,使用什么属性由用户在运行时决定.我想避免创建具有很多空属性的对象.

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.

推荐答案

也许代理类可能很有趣.

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());

动物不需要实现任何接口,但是您可以查找(lookupas)功能.这是将来可扩展的,动态的:可以在运行时更改.

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.

实施为

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.

这篇关于选择要在运行时实现的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-10 21:56