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?
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
Use the instanceof operator to check if an object is an instance of a class, e.g. if (myObj instanceof MyClass) {} . The instanceof operator checks if the prototype property of the constructor appears in the prototype chain of the object and returns true if it does. Copied!
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
.
I'm assuming you are implementing some sort of Specification/Protocol or similar.
This is similar to what Programming Languages are doing with literals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With