Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error on storing a method in a variable

Tags:

java

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).

like image 781
Simon Klaver Avatar asked Jan 04 '16 12:01

Simon Klaver


People also ask

Can I store a function in a variable?

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.

Can you store a method in a variable Java?

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.

Can I store a function in a variable python?

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.

How do you store things in a variable?

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.


2 Answers

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;
like image 91
Konstantin Yovkov Avatar answered Oct 05 '22 23:10

Konstantin Yovkov


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).

like image 32
Eran Avatar answered Oct 05 '22 22:10

Eran