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?
I would consider using the JavaBeans
PropertyEditor
mechanism for this.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.I'm assuming you are implementing some sort of Specification/Protocol or similar.
This is similar to what Programming Languages are doing with literals.
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:
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.
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):
I'm taking into account the fact that, every wrapper class has a static
valueOf
method that takes a parameter of typeString
, and returns the value of thatwrapper
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 ofclazz
type.P.S.: Note that for
Boolean.class
, any string that is not"true"
will be treated asfalse
.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.
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.