1

So, I've tried to get object type of a given class to parse into ArrayList Example:

public class Util{
    public static void makeArray(String tag, Class<?> forClass) {
        ArrayList<?> list = new ArrayList();
    }
}

How can I replace <?> with forClass object type? So back in main method when I call

Util.makeArray("names", String.class);

It would create ArrayList<String> and if I say

Util.makeArray("ages", int.class);

It would resolve it to ArrayList<Integer>

And if it is not even done this way, show how.

1 Answer 1

3

You would use a method type parameter.

public static <T> void makeArray(String tag, Class<T> forClass) {
    ArrayList<T> list = new ArrayList<>();
}

This can be called using Util.<String>makeArray("names", String.class) or you can let the compiler infer T by omitting the <String>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.