6
votes

I was looking at a way to optimize some things in our code base with generic functions. There is a function with return type List<Object> which could have return type List<SpecifiedType>.

Bellow is a minimalist version of that function called function. It takes a parameter type, based on it calls a corresponding function (here limited to String) or generic function.

public static ArrayList<String> forString(){
    ArrayList<String> res = new ArrayList<>();
    // Fetching and processing data specific to String
    return res;
}

public static <T> ArrayList<T> forGeneric(Class<T> type){
    ArrayList<T> res = new ArrayList<>();
    // Fetching data
    return res;
}

public static <T> ArrayList<T> function(Class<T> type){
    if(type == String.class)
        return (ArrayList<T>) forString();
    return forGeneric(type);
}

The target is for function above to be called like this: ArrayList<SomeType> someTypes = function(SomeType.class);

Two things I've noticed about the code above:

  1. Cast to ArrayList<T> is required even though we know that if type String is passed as a parameter it will return ArrayList<String> just like forString() method

  2. Cast to ArrayList<T> gives Unchecked cast warning, even though the return type will be ArrayList<String>

My question is is there some better way to do so (preferably without the casts) and if not, then why

2
Umm... forString and forGeneric return the same thing (after type erasure). Maybe you could extend the example to make clear what the actual goal should be? - Marco13
I wanted to provide as minimal example as possible. In the actual code "forString" methods are doing additional thing specific for the type they return. - Miku
Even though you need a cast in your java code, it will be stripped away when you are compiling, as the classes are the same. After compilation all generics are removed - Ferrybig

2 Answers

4
votes

First off, this statement is logically wrong

if(type.isInstance(String.class))

If type is Class<String> then isInstance is checking to see if the argument is a string instance. The argument you are passing is a class instance (specifically, a Class<String>).

If you prefer,

String.class.isInstance(String.class) == false

What you meant was

if(type == String.class)

However, even with this logical error resolved, your code will still have an unchecked cast warning.

The part you are missing is right here

Cast to ArrayList<T> is required even though we know that if type String is passed as a parameter it will return ArrayList<String> just like forString() method

Exactly. We know it. But what we know and what the compiler knows are two different things. The compiler is not clever enough to check the conditional and realise that the type is okay. It conceivably could be smart enough, but it is not.

This is precisely why this manifests as a warning and not as an error. It is a warning because what you are doing is potentially wrong; it is not definitely wrong, else it would not compile at all. In this case, the warning should act as a prompt for you to double-check that what you're doing is correct and then you can happily suppress it.

@SuppressWarnings("unchecked")
public static <T> ArrayList<T> function(Class<T> type){
    if(type == String.class)
        return (ArrayList<T>) forString();
    return forGeneric(type);
}

Finally -- and it may be an artifact of your contrived example -- but all of these methods are useless. There does not seem to be any advantage over calling new ArrayList<>() directly. At runtime, the actual instances are identical regardless of which of the 3 methods it came from.

0
votes

There is no way for runtime code to return different generic types based on runtime information, because generics are a compile-time mechanism.

To be truly free of compiler warnings, I would return a new List:

public static <T> ArrayList<T> function(Class<T> type){
    ArrayList<?> result;
    if (type.equals(String.class)) {
        result = forString();
    } else {
        result = forGeneric(type);
    }

    ArrayList<T> typedResult = new ArrayList<>(result.size());
    for (Object item : result) {
        typedResult.add(type.cast(item));
    }

    return typedResult;
}

This might seem wasteful, but it’s not. The new List is not a list of new objects, just new references. A reference is pretty small, probably not more than 256 bytes, so a list of 4,000 objects would take up no more than a megabyte of RAM.