我要禁止显示“未经检查的演员表”警告,还是可以更好地对其进行编码?

时间:2019-03-07 11:29:52

标签: java

如果我从这段代码中取出@SuppressWarnings("unchecked"),则会得到:

  

Unchecked cast: 'java.lang.Class<capture<?>>' to 'java.lang.Class<? extends com.megacorp.security.User>'

查看稍后在代码中如何使用获取引用的构造函数。我可以重构它还是只需要忍受它?

private final Constructor<? extends User> constructor;

public LdapUserDetailsMapper(String userClassName)
        throws ClassNotFoundException, NoSuchMethodException {
    @SuppressWarnings("unchecked") 
    Class<? extends User> userClass =
            (Class<? extends User>) Class.forName(userClassName);
    constructor = userClass.getConstructor(String.class, Collection.class);
    if (constructor == null) {
        throw new IllegalArgumentException(String.format(
                "Couldn't find user constructor for [%s]", userClassName));
    }
}

@Override
public UserDetails mapUserFromContext(String login,
        Collection<? extends GrantedAuthority> authorities) {
    //Extract basic user info
    User user;
    try {
        user = constructor.newInstance(login, mergedAuthorities);
        return user;
    } catch (IllegalAccessException
            | InstantiationException
            | InvocationTargetException e) {
        throw new RuntimeException(
                String.format("Cannot instantiate new User [%s]", login),
                e);
    }
}

0 个答案:

没有答案