简体   繁体   English

如何传递数据类型,例如字符串,日期

[英]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. 我可以用不同的方式做到这一点,例如用一个表示类型,枚举等的不同值声明一个int。

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 如果您希望将对象的类型作为参数传递,则可以通过传递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: 您可以使用instanceof运算符:示例:

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: 但这是不好的样式,因为您没有类型save的类型,最好是重载该方法:

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 您可以通过在类名称上“调用” .class来获得类型,它将返回代表该类型的Class的实例

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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