Java how to check if a string value is a type of g

2019-02-08 03:08发布

Alright this is kind of a complicated question and I'm completely lost.

Assume you have a string, and a generic class. Like this.

String string;
Class<?> clazz;

How would you check to see if the String represented a value that the class could equal.

For example lets say that:

String string = "true";
Class<?> clazz = Boolean.class;

How would I check and see that the string "true" is in fact a boolean?

Here is another example. Lets say that:

String string = "true";
Class<?> clazz = Integer.class;

How would I check and see that the string "true" is not an Integer?

5条回答
干净又极端
2楼-- · 2019-02-08 03:27

I would consider using the JavaBeans PropertyEditor mechanism for this.

@Test
public void testIsOfType() {        
    assertFalse(test("nope", Integer.class));
    assertFalse(test("nope", Boolean.class));

    assertTrue(test("1", Integer.class));
    assertTrue(test("true", Boolean.class));
}

boolean test(String str, Class<?> clazz) {
    PropertyEditor propertyEditor = PropertyEditorManager.findEditor(clazz);
    if (propertyEditor != null) {
        try {           
            propertyEditor.setAsText(str);
            return true;
        } catch (Exception ex) {}
    }
    return false;
}

This avoids the need for explicit reflection, and if you ever decided you needed to test classes other than the primitive wrappers you could register a new editor with PropertyEditorManager.registerEditor().

Unfortunately this still has the problem that Rohit's solution has in that test("1", Number.class) will fail.

查看更多
叛逆
3楼-- · 2019-02-08 03:28

I'm assuming you are implementing some sort of Specification/Protocol or similar.

  1. Look at the Spec.
  2. Define a Grammar of valid input
  3. Parse that grammar.

This is similar to what Programming Languages are doing with literals.

查看更多
Evening l夕情丶
4楼-- · 2019-02-08 03:36

In javascript you could eval() the string. In Java you don't have such means. You'll have to implement your own heuristics for this check.

The one thing you can do however, is try to parse the string with the given class. Like:

Iteger.parseInt(stringValue);

If the parse succeeds, then the string can be used as a value for that type. If it fails, then you get an exception. Implement these checks and then deduct some conclusion.

查看更多
女痞
5楼-- · 2019-02-08 03:37

Given that you want this only for Wrapper Types, you can use some reflection hack here (Exception handling for irrelevant code is ignored here for brevity):

String string = "ABC";
Class<?> clazz = Integer.class;

Method method = clazz.getDeclaredMethod("valueOf", String.class);

if (method != null) {
    try {
        Object obj = method.invoke(null, string);       
        System.out.println("Success : " + obj);

    } catch (InvocationTargetException ex) {
        System.out.println("Failure : " + string + " is not of type " + 
                                          clazz.getName());
    }
}

I'm taking into account the fact that, every wrapper class has a static valueOf method that takes a parameter of type String, and returns the value of that wrapper type. And throws an exception, if the parameter is not convertible to the respective wrapper type.

So, in above case, if an exception is thrown, the string value is not of clazz type.

P.S.: Note that for Boolean.class, any string that is not "true" will be treated as false.

查看更多
Anthone
6楼-- · 2019-02-08 03:40

I'm not able to test this solution right now, but why not something like this? If you can enumerate all of the possible classes yourself, just create some switch statements on the class.

boolean isStringClass (Class clazz, String string) {

    try {
        if (Integer.class == clazz) {
           Integer.valueOf(string);
        } else if (Boolean.class = clazz) {
           Boolean.valueOf(string);
        } [...etc]
    } catch (Exception e) {
        return false;
    }

    return true;
}

Of course you will need to know all of the possible classes, and you will need to know of a method that belongs to that class that is able to parse a String and return its type. For the primitive wrappers that would be valueOf.

If you plan on only converting wrappers, Rohit's solution would be a better choice. However, if you're not doing that and you're unable to add a valueOf method to this new Class, this may be your only option.

查看更多
登录 后发表回答