Maik Klein
Maik Klein

Reputation: 16168

Java reflection/generics

public static <T> T inCache(T obj) throws ClassNotFoundException {
        String[] token = validateCookie(); //gives me to strings
        if (token == null)
            return null;
        if (Cache.get(token[0]) != null) {
            if (Cache.get(token[0]).getClass() == Class.forName(token[1])
                    && obj.getClass() == Cache.get(token[0]).getClass()) {
                T test = (T) Cache.get(token[0]);
                return test;
            }
        }
        return null;
    }

The code above is completely wrong.

Basicly I want to do something like this:

I want to use it like this.

User user = inCache<User>();

Upvotes: 1

Views: 186

Answers (1)

Thomas
Thomas

Reputation: 88757

As for the class signature, why don't you use something like this:

public static <T> T inCache(Class<T> clazz) throws ClassNotFoundException {
  ...
}

And then call it like this:

User user = inCache(User.class);

Generics can't be used the way you described (User user = inCache<User>();) due to type erasure at runtime, i.e. the type of T is unknown at runtime in that case.

Also note that it might be better to test using Class#isAssignableFrom(...) to be able to check for subclasses as well, e.g. clazz.isAssignableFrom(Cache.get(token[0]).getClass()). That way you could pass an interface or super class and still get a match if the object is of a subtype.

Upvotes: 6

Related Questions