Casting a clan class. (cast) vs Class.cast ()

I searched my use case and found interesting answers, but they are not suitable for me. What would be the appropriate way:

@SuppressWarnings("unchecked")
public <T> T newInstance(String name) throws ClassCastException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    return (T) loadClass(name).newInstance();
}

or a little different:

public <T> T newInstance(String name, Class<T> c) throws ClassCastException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    return c.cast(loadClass(name).newInstance());
}

I think both methods do the same. From my point of view, method 1 is better due to smaller parameters. Both throw a ClassCastException, which will be good for me. In truth, the annotation is @SuppressWarnings("unchecked")not very pleasant.

Can someone tell me if there are any advantages to one method for another?

Edit: Jon Skeet answer is correct. The following passage may provide further clarification.

public class Test {
    public static void main(String[] args) {
        Object o = new Object();
        // Exception at c.cast(o)
        Test.<String>realCast(o, String.class);
    }

    private static <T> T realCast(Object o, Class<T> c) {
        return c.cast(o);
    }
}

realCast() , o c. , fakeCast() , T.

+4
1

, .

, . T - . , . T, , ( T, ), .

:

public class Test {
    public static void main(String[] args) {
        Object o = new Object();
        // No exception
        Test.<String>fakeCast(o);
        // Exception at the point of assignment:
        // the code is effectively String x = (String) ...;
        String x = Test.<String>fakeCast(o);
    }

    private static <T> T fakeCast(Object o) {
        return (T) o;
    }
}

T Class<T>, , , .

+7

All Articles