在Java中,可以指定任意数量的泛型类型参数吗? [英] In Java, can I specify any amount of generic type parameters?

查看:107
本文介绍了在Java中,可以指定任意数量的泛型类型参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在Java 中创建一种特殊类型的接口(尽管这同样适用于常规类).该接口需要包含一些方法,例如 invoke ;会根据提供的泛型类型参数使用不同数量的参数来调用它.

I am looking to create a particular type of interface in Java (although this is just as applicable to regular classes). This interface would need to contain some method, say, invoke; it would be called with a varying amount of parameters depending on the generic type arguments supplied.

例如:

public interface Foo<T...> {
    public void invoke(T... args);
}

// In some other class
public static Foo<Float, String, Integer> bar = new Foo<Float, String, Integer>() {
    @Override
    public void invoke(Float arg1, String arg2, Integer arg3) {
        // Do whatever
    }
};

简单地说明一下如何使用它(并提供一些上下文),请考虑一个类 Delegator :该类采用不同数量的泛型类型,并且具有这些参数类型的单一方法- invoke .该方法将其参数传递给列表中的一个对象: IDelegate 的实例,该实例采用相同的泛型类型.这样, Delegator 可以在几种委托方法(在 IDelegate 内部定义)之间进行选择,而不必为每个特定的参数类型列表创建新的类.

To explain, briefly, how this could be used (and provide some context), consider a class Delegator: the class takes a varying number of generic types, and has a single method - invoke, with these parameter types. The method passes on its parameters to an object in a list: an instance of IDelegate, which takes the same generic types. This allows Delegator to choose between several delegate methods (defined inside IDelegate) without having to create a new class for each specific list of parameter types.

有没有类似的东西?我已经阅读了有关C ++中的 variadic模板的信息,但是在Java中找不到任何类似的东西.有这样的东西吗?如果没有,那么模拟相同数据模型的最干净方法是什么?

Is anything like this available? I have read about variadic templates in C++, but cannot find anything similar in Java. Is any such thing available? If not, what would be the cleanest way to emulate the same data model?

推荐答案

有没有类似的东西?我已经阅读了有关可变参数模板的信息在C ++中,但是找不到在Java中类似的东西.有这样的事吗有空吗?

Is anything like this available? I have read about variadic templates in C++, but cannot find anything similar in Java. Is any such thing available?

否,该功能在Java中不可用.

No, this feature is not available in Java.

这篇关于在Java中,可以指定任意数量的泛型类型参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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