如何声明一个类<?>对象,这是一个枚举和Java中的接口 [英] How to declare a Class<?> object such that is is an Enum AND an Interface in Java

查看:180
本文介绍了如何声明一个类<?>对象,这是一个枚举和Java中的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实用程序类需要在泛型类上工作,但必须限制为那些枚举类型并实现特定接口的类。

  //这两个工作
Class< ;?扩展Enum<>> enumClass;
Class <?扩展MyInterface> interfaceClass;

//这是我想要的,但不起作用
Class< ;?延伸MyInterface&枚举<?>> enumAndInterfaceClass;

对于泛型,我可以成功使用这个

  public class MyClass< T extends Enum< T> &安培; MyInterface的> {
public MyClass(Class< T> theClass){
...
}
}

然而,我无法在任何地方使用泛型,需要单独声明它。我不确定这是否可能。
-
所以我的问题归结为如何用这些约束声明一个成员变量?

所以目前MyClass是一个单例,然后根据需要可以更新枚举/接口。其操作的返回值将根据给定的枚举而变化。我想没有它的泛型,因为这将需要为枚举的每个更改创建一个新实例。已经有很多代码使用它,所以偏离单例不会被批准。所以必须保留一个参考。我想我只能强制执行接口要求,然后在setter方法中检查它是否是一个抛出异常的枚举,否则这并不理想。



编辑(更新了问题并增加了更多详细信息) / div>

据我所知,只能声明交集类型(这是& 创建的)类型参数类和方法。你不能直接用交集类型声明局部变量;你可以借助类或方法类型参数创建这样的变量,如milkplusvellocet的答案所示。



请参阅此答案中的JLS参考以解决类似的问题:
https://stackoverflow.com/a/6643378/282229


I have a utility class that needs to work on a generic Class but must be restricted to those that are an enum and implement a particular interface.

// These two work
Class<? extends Enum<?>> enumClass;
Class<? extends MyInterface> interfaceClass;

// This is what I want but does not work
Class<? extends MyInterface & Enum<?>> enumAndInterfaceClass;

For generics I can successfully use this

public class MyClass<T extends Enum<T> & MyInterface> {
    public MyClass(Class<T> theClass) {
        ...
    }
}

However I can't use the Generics everywhere and need to declare it separately. I am not sure if this is even possible.
So my question boils down to how can I declare a member variable with those constraints?

So Currently MyClass is a singleton then as needed the enum/interface can be updated. The return values of its operations will change depending on which enum it is given. I would like to not have the generics on it since that would require creating a new instance for every change to the enum. There is a lot of code using it already so deviating from the singleton is not going to be approved. So a reference must be kept. I suppose I could only enforce the Interface requirement then check in the setter method that it is an enum throwing an exception otherwise but that is not ideal.

Edit (Updated question and added more detail)

解决方案

As far as I remember, you can only declare intersection types (this is what & creates) for type parameters of classes and methods. You can not declare a local variable with an intersection type directly; you can create such variables with the aid of a class or method type parameter, as seen in the answer of milkplusvellocet.

See the JLS reference in this answer to a similar question: https://stackoverflow.com/a/6643378/282229

这篇关于如何声明一个类&lt;?&gt;对象,这是一个枚举和Java中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆