开发者

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 ela开发者_开发百科borate, 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

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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜