简体   繁体   中英

How to pass a datatype like String, Date

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.

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

ie

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.

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");
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM