How to pass a type as a method parameter in Java

By | August 5, 2019

Question

In Java, how can you pass a type as a parameter (or declare as a variable)?

I don’t want to pass an instance of the type but the type itself (eg. int, String, etc).

In C#, I can do this:

private void foo(Type t)
{
    if (t == typeof(String)) { ... }
    else if (t == typeof(int)) { ... }
}

private void bar()
{
    foo(typeof(String));
}

Is there a way in Java without passing an instance of type t?
Or do I have to use my own int constants or enum?
Or is there a better way?

Edit: Here is the requirement for foo:
Based on type t, it generates a different short, xml string.
The code in the if/else will be very small (one or two lines) and will use some private class variables.

Solution

You could pass a Class<T> in.

private void foo(Class<?> cls) {
    if (cls == String.class) { ... }
    else if (cls == int.class) { ... }
}

private void bar() {
    foo(String.class);
}

Update: the OOP way depends on the functional requirement. Best bet would be an interface defining foo() and two concrete implementations implementing foo() and then just call foo() on the implementation you’ve at hand. Another way may be a Map<Class<?>, Action> which you could call by actions.get(cls). This is easily to be combined with an interface and concrete implementations: actions.get(cls).foo().

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *