tags:

views:

51

answers:

3

Say I have a method declaration like:

private void someMethod(final String someKey, final Object dataType){
  // Some code
}

I want to call it like:

someMethod("SomeKey", String);
someMethod("SomeKey", Date);

I can it do it in different ways like declaring an int with different values representing the type, an enum, or the like.

But can I just pass the type itself?

EDIT:

To elaborate, I can do like:

someMethod("SomeKey", 1); // 1 = String
someMethod("SomeKey", 2); // 2 = Date

This doesn't look good.

+4  A: 

If you're looking to pass the type of object as a parameter, you can do it by passing a java.lang.Class

i.e.

public void someMethod( String someKey, Class clazz ) {
    ... whatever
}

Is that what you're looking for?

edit: incorporating Mark's comment.

You can call this like

someMethod( "keyA", Date.class );
someMethod( "keyB", String.class );

etc.

Shawn D.
Wouldn't that be expensive?
James Smith
Expensive in terms of construction? That's a class literal (http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#251530). It's a compile-time thing. It's really hard to figure out what you're asking. Could you describe what it is you want your method to do, even at a basic level?
Shawn D.
Many thanks for the link.
James Smith
A: 

You could use the instanceof operator: example:

private void someMethod(String someKey, Object dataType) {
    if (dataType instanceof String) {
        System.out.println("Called with a String");
    }
    else if (dataType instanceof Date) {
        System.out.println("Called with a Date");
    }
}

But this is bad style because you do not have type savety, it is better, to overload the method:

private void someMethod(String someKey, String dataType) {
    System.ount.println("Called with a String");
}

private void someMethod(String someKey, Date dataType) {
    System.ount.println("Called with a Date");
}
BitSchupser
Why exactly do you need type safety here when you are not gonna process something that doesn't fall under any of your instanceof condition?
James Smith
A: 

You can get a type by "calling" .class on a class name, it will return an instance of Class that represents the type

private void someMethod(final String someKey, final Class<?> dataType){
// Some code
}

someMethod("SomeKey", String.class);
someMethod("SomeKey", Date.class);
arjan