简体   繁体   中英

How does the Java Class class getMethod function work?

I'm studying this code about Java Inheritance(from Core 2 java bk by Hoffman), and here's a code in the class MethodPointerTest.java :

Method square = MethodPointerTest.class.getMethod("square", double.class);

Later in the class there'sa function like so:

public static double square(double x){ 
return x * x;
}

why is the seocnd argument of the getMethod function:

double.class

Vs just saying "double"

Thank You

The getMethod() method takes Classes as parameters to represent the type of the method's parameter(s).

The keyword double is only used to declare or cast a variable/parameter.

With reflection, you're dealing with meta-code, not code.

The reason you need to add Double.class is because you can overload methods in java. That means that you can have many methods with the same name, but different parameters. Because of this java allows you to specify both the name of the method and the type of its parameters when retrieving it with reflection.

The reason you need Double.class rather than just double is that double isn't a type, it's a double. Double.class is a type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM