如何在Java中为复杂的泛型类型创建别名?

时间:2014-12-17 11:57:08

标签: java syntax types alias

我有这段代码:

Callable<Map<String, List<com.w.automation.rtsimulator.headlessclient.data.SearchResult>>> callable = new
                Callable<Map<String, List<com.w.automation.rtsimulator.headlessclient.data.SearchResult>>>() {
            @Override
            public Map<String, List<com.w.automation.rtsimulator.headlessclient.data.SearchResult>> call() throws
                    Exception {
                Map<String, List<com.w.automation.rtsimulator.headlessclient.data.SearchResult>> searchResults =
                        Foo());
                return searchResults;
            }
        };

如何缩短Map<String, List<com.w.automation.rtsimulator.headlessclient.data.SearchResult>>

类型

语法上的糖更短?

修改

我想让它更短。我如何将其别名为“MyClass”

4 个答案:

答案 0 :(得分:1)

您可以创建包裹这些类型并使用它们的clases:

class WrapClass {
    Callable<Map<String, List<com.w.automation.rtsimulator.headlessclient.data.SearchResult>>>     callable;
etc...

答案 1 :(得分:0)

import com.w.automation.rtsimulator.headlessclient.data.SearchResult;

Callable<Map<String, List<SearchResult>>> callable = new
    Callable<>() { // this works from Java 7
            @Override
            public Map<String, List<SearchResult>> call() throws Exception {
                return Foo();
            }
    };

答案 2 :(得分:0)

真的不清楚你真正想要什么,但你可以声明,例如:

public final class MyClass
    implements Callable<Map<String, List<SearchResult>>>
{
    // Instance variables, constructor(s) and stuff

    @Override
    public Map<String, List<SearchResult>> call()
        throws SomeException // <-- DO NOT throw Exception
    {
        // implementation
    }
}

答案 3 :(得分:0)

这应该可以解决问题:

import com.w.automation.rtsimulator.headlessclient.data.SearchResult;

Callable<MyClass> callable = new Callable<MyClass>() {
    @Override
    @SuppressWarnings("unchecked")
    public MyClass call() throws Exception {
        return (MyClass) Foo();
    }
};

您还需要定义MyClass:

public class MyClass extends Map<String, List<SearchResult>> {
    // implement whatever code you want here for your class objects
}