Java Generics:为每个内部类构建参数化类

时间:2012-12-19 21:57:32

标签: java generics

说我有一个界面:

public interface Authentication<T> {
   public void authenticate(T token);
}

我有一个名为AuthenticationMethods的类,它有几个内部类。

我想要做的是编写一个实用程序,我可以获取所有内部类,并生成一个实现内部类的Authentication<T>类型T接口的类,如下所示:

for (Class clazz : AuthenticationMethods.class.getDeclaredClasses()){
   createAuthenticationImplClass(clazz);
}

private <T> Authentication<T> createAuthenticationImplClass(Class clazz){
  return new Authentication<clazz>() {
     @Override
     public void authenticate(clazz token) throws Exception {
        //do something with the token
     }
   };
}

显然,仅使用clazz代替T不起作用。

如何将clazz中的类型转换为Authentication接口的参数化实现?

2 个答案:

答案 0 :(得分:3)

你可以这样做。

private <T extends Class<?>> Authentication<T> createAuthenticationImplClass(T clazz){
  return new Authentication<T>() {
     @Override
     public void authenticate(T token) throws Exception {
        //do something with the token
     }
   };
}

实施例

Authentication<Class<String>> = createAuthenticationImplClass(String.class);

或者

private <T> Authentication<T> createAuthenticationImplClass(Class<T> clazz){
  return new Authentication<T>() {
     @Override
     public void authenticate(T token) throws Exception {
        //do something with the token
     }
   };
}

示例:

Authentication<String> = createAuthenticationImplClass(String.class);

不同之处在于,在第一个示例中,您的authenticate方法将在参数中包含Class类型。在第二个参数将是类表示的类型。

答案 1 :(得分:1)

如果我理解正确,您需要验证clazz类的令牌。然后,您需要使用通用类类型参数化工厂方法参数:

private <T> Authentication<T> createAuthenticationImplClass(Class<T> clazz){
    return new Authentication<T>() {
        @Override
        public void authenticate(T token) throws Exception {
            //do something with the token
        }
    };
}

当然,当你为声明的类执行 for 循环时,会丢失泛型类型,因此传递类型安全Class实例的唯一方法是显式类名:

Authentication<TokenType> authForTokenType = createAuthenticationImplClass(TokenType.class);