I'm using reflection to call a method in Java. I'd like to see if the value that potentially is to be passed into the method is of the right type before I invoke the method.
My initial idea was to get the class of the parameter via method.getParameterTypes()
and then compare that type to the type of the object that I'd like to pass in. If it's a subclass, then proceed.
However, this fails on a method that takes a primitive. If I have a method:
private void doThing(boolean parp) {}
The return value of getParameterTypes
for this indicates that the type of the parameter is a class called boolean
in the java.base
module. However, I might be wanting to pass in a value which is of type java.lang.Boolean
, which although is perfectly legal to pass in, doesn't sit in the type hierarchy. java.lang.Boolean
isn't a subclass of, or apparently in any way related to boolean
.
What test can I use against a method's given parameter type and the type of a given object to determine whether its legal to pass that object into the method?
Aucun commentaire:
Enregistrer un commentaire