首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java泛型varargs方法参数

Java泛型varargs方法参数
EN

Stack Overflow用户
提问于 2013-03-12 17:25:43
回答 6查看 7.1K关注 0票数 18

我想知道是否有一种简单的、优雅的和可重用的方法来将字符串和字符串数组传递给期望使用varargs的方法。

代码语言:javascript
复制
/**
 * The entry point with a clearly separated list of parameters.
 */
public void separated(String p1, String ... p2) {
    merged(p1, p2, "another string", new String[]{"and", "those", "one"});
}

/**
 * For instance, this method outputs all the parameters.
 */
public void merged(String ... p) {
    // magic trick
}

即使所有类型都是一致的(String),我也找不到告诉JVM扁平化p2并将其注入到合并的参数列表中的方法。

此时,唯一的方法是创建一个新数组,将所有内容复制到其中,并将其传递给函数。

有什么想法吗?

编辑

根据您的建议,下面是我将使用的泛型方法:

代码语言:javascript
复制
/**
 * Merge the T and T[] parameters into a new array.
 *
 * @param type       the destination array type
 * @param parameters the parameters to merge
 * @param <T>        Any type
 * @return the new holder
 */
@SuppressWarnings("unchecked")
public static <T> T[] normalize(Class<T> type, Object... parameters) {
    List<T> flatten = new ArrayList<>();
    for (Object p : parameters) {
        if (p == null) {
            // hum... assume it is a single element
            flatten.add(null);
            continue;
        }
        if (type.isInstance(p)) {
            flatten.add((T) p);
            continue;
        }
        if (p.getClass().isArray() && 
            p.getClass().getComponentType().equals(type)) {
            Collections.addAll(flatten, (T[]) p);
        } else {
            throw new RuntimeException("should be " + type.getName() + 
                                             " or " + type.getName() + 
                                             "[] but was " + p.getClass());
        }
    }
    return flatten.toArray((T[]) Array.newInstance(type, flatten.size()));
}

normalize(String.class, "1", "2", new String[]{"3", "4", null}, null, "7", "8");
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15357439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档