Mdhar9e
Mdhar9e

Reputation: 1376

Bound mismatch error using Generics

When I tried to compile my previous java 1.4 code in 1.5 I got this generics Bound mismatch problem. The code is given below

try {
    ArrayList simplePrincipals = new ArrayList(
            ((java.util.Collection) (subject.getPrincipals(Class
                    .forName("com.efunds.security.jaas.SimplePrincipal")))));
    if (simplePrincipals.size() > 0) {
        ((SimplePrincipal) simplePrincipals.get(0))
                .setPermissions(webPerm);
    }
}

the error is :

Bound mismatch: The generic method getPrincipals(Class<T>) of type Subject is not applicable for the arguments (Class<capture#1- of ?>). The inferred type capture#1-of ? is not a valid substitute for the bounded parameter <T extends Principal>

Upvotes: 2

Views: 2239

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

If you look at the Javadocs, you'll see that getPrincipals() is now defined to take a Class<T extends Principal> -- i.e., a Class object representing a subclass of Principal. Your code has to take this into account, for example, by using the asSubclass() method:

String className = "com.efunds.security.jaas.SimplePrincipal";
Class<? extends Principal> clazz =
    Class.forName(className).asSubclass(Principal.class); 
ArrayList<Principal> simplePrincipals =
    new ArrayList<Principal>(subject.getPrincipals(clazz));

Note that your cast to Collection as well as most of the parentheses are unnecessary.

Upvotes: 5

Related Questions