Reputation: 28907
Suppose I have the following three classes
A.java
public class A {
public static void main (String[] args) {
new C();
}
}
B.java
import java.lang.reflect.Method;
import java.util.Arrays;
public class B {
public B() {
Method[] m = this.getClass().getDeclaredMethods();
System.out.println(Arrays.toString(m));
}
public void hello() {
}
}
C.java
public class C extends B{
public C() {
super();
}
}
and I run the main method in class A. Well, it should instantiate class C, which in turn should call class B's constructor, to print out the declared methods. The output is []
. This is a surprise to me, as I was expecting the output to be (assuming all classes are in package called test
):
[public void test.B.hello()]
So, what's wrong? And how do I get it so that this is the actual output?
Upvotes: 1
Views: 3244
Reputation: 1
//Actually one can get the number of methods in different classes under the //different packages....
//Go and check the results................
import java.lang.reflect.Method;
public class TestPackage {
public static void main(String args[]) throws ClassNotFoundException
{
int count=0;
Class c=Class.forName("java.util.Scanner");
Method[] m=c.getDeclaredMethods();
for(Method m1:m)
{
count++;
System.out.println(m1.getName());
}
System.out.println("The no. of methods are:"+count);
}
}
Upvotes: 0
Reputation: 3848
The key here is use of the word this
That implies the present context, which if C
is a concrete subclass of B
is C
. To get B's
methods, you need to traverse until you get to B. That's probably application logic dependent. One way would be the following.
import java.lang.reflect.Method;
import java.util.Arrays;
public class B {
public B() {
Class<?> parent = getClass();
while(parent.getSuperclass() != null) {
if(parent.getSuperclass() != Object.class) {
parent = parent.getSuperclass();
} else {
break;
}
}
Method[] m = parent.getDeclaredMethods();
System.out.println(Arrays.toString(m));
}
public void hello() {
}
}
Upvotes: 1
Reputation: 5843
getClass
returns the class of the instance. In this case, this is C
. There is no declared method in class C
. You can solve your problem by also using the 'getSuperClass' method of the returned Class
object:
Class c = this.getClass();
while (c != null) {
System.out.println(Arrays.toString(c.getDeclaredMethods()));
c = c.getSuperClass();
}
Upvotes: 4