Class c = v.getClass();
try {
Method m = c.getMethod("something");
if(!m.getReturnType().equals(Boolean.TYPE)) {return false;}
} catch(NoSuchMethodException e) {return false;}
...where v
is an object of a certain class.
When I try to compile this, I get:
error: cannot find symbol
Method m = c.getMethod("something");
^
Method is a type which resides in java.lang.reflect.Method
. By my knowledge java.lang
and anything subsequent is imported by default, but I even did so explicitly:
import java.lang.*;
So my question is: How can I either make my compiler recognise the class Method
, or how can I store the returnvalue of getMethod
otherwise?
P.S: Please ignore the unchecked call to getMethod, that will be a problem for a different time (so a different question, probably).
Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.
Calling a Method With a Return Value Fortunately, we can store a method's return value into a variable. Take a look at the following code: int num = 7; int tenAdded = addTen(7); First, we create a variable named num and initialize it to 7.
In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.
To store a value in a variableUse the variable name on the left side of an assignment statement. The following example sets the value of the variable alpha . The value generated on the right side of the assignment statement is stored in the variable.
The classes from the java.lang.
package are automatically imported, but this does not apply for the nested packages. And this is true not only for java.lang.*
, but for all packages in general - nested packages are not automatically imported and if you need some class from a nested package, you should explicitly import it. Like this:
import java.lang.reflect.Method;
You need to import java.lang.reflect.Method
or java.lang.reflect.*
. Importing java.lang.*
doesn't include the java.lang.reflect
package, since java.lang.reflect
is not a sub-package of java.lang
(there is no package hierarchy in Java).
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