Reputation: 12484
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
Upvotes: 1
Views: 207
Reputation: 16100
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.
Upvotes: 2
Reputation: 425003
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.
Upvotes: 4