Using Java, I have a method which I’m calling with method.invoke that returns a string.
Method.invoke returns an object though which can’t be cast to String.
How am I supposed to use the Object as a string??
In the docs on reflection it shows the following:
Object o = m.invoke(t, new Locale(args[1], args[2], args[3]));
out.format("%s() returned %b%n", mname, (Boolean) o);
But my code does this and I get an exception: java.lang.Class cannot be cast to java.lang.String
This is an abstract class – there will then be several implementations of beans.
Method[] methods = this.getClass().getMethods();
for (Method method : methods) {
if (isMethodGetter(method)) {
try {
Object message = method.invoke(this); // expect a string
Object message = method.invoke(this); // expect a string
if (message == null) {
// no messeage
} else {
logger.debug("Calling listAnswers: got an answer: "
+ message);
// create an answer object from the reflected
Answer answer = new Answer();
answer.setText((String)message);//cast as string
answerList.add(answer);
}
edit: as per below answers I had a problem with the validation.
It’s simple: you didn’t get an instance of
java.lang.String, but ofjava.lang.Class. Your clarification in the comment makes it all crystal-clear: the methodjava.lang.Object.getClasspasses yourisMethodGettertest, but it’s not want you wanted. Just enhance that checking code to not let the exact namegetClasspass.