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.
You could pass a
Class<T>in.Update: the OOP way depends on the functional requirement. Best bet would be an interface defining
foo()and two concrete implementations implementingfoo()and then just callfoo()on the implementation you’ve at hand. Another way may be aMap<Class<?>, Action>which you could call byactions.get(cls). This is easily to be combined with an interface and concrete implementations:actions.get(cls).foo().