Reputation: 654
So, this is going to sound like an odd question, but I need to know how to get the Class
object of a child Object
in an inheritance situation for Java reflection.
The situation is this: I'm writing CraftBukkit plugins, Java plugins that work with CraftBukkit, a server-side-only plugin A.P.I. for Minecraft. At the moment, I'm making a plugin that is supposed to be like a "parent" to all of the other plugins I'm writing. It contains large amounts of extra useful Objects and utilities.
One class in the plugin is an Object class called myPlugin
that I want all the main classes of all the other plugins to extend
. (I know Object names shouldn't start with a lowercase letter, but the lowercase "my" is a trademark with my CraftBukkit plugins.)
One of the things that I want this myPlugin
class to do is be able to handle commands to load plugins' data. Therefore, when the command is called, I want the plugin to basically call all of the methods in the plugin's main class that start with "load".
I know how to search through all the Methods in the Class
for ones starting with "load" if I can just retrieve the Class
, but if I try to call getClass()
in the myPlugin
class, I believe it's just going to return the myPlugin
Class
instead of the Class
that extends myPlugin
.
So, how can I retrieve the Class
that extends myPlugin
instead of the myPlugin
class itself?
EDIT:
I feel that I should mention that I've considered creating an abstract
method called mainClass()
that will return the Class and making each plugin add this method and return their main class, but this is an ugly fix that I would prefer to avoid.
Upvotes: 0
Views: 1442
Reputation: 114
No it's the subclass name that is returned, consider:
public class ClassOne {
}
public class ClassTwo extends ClassOne {
}
public class Test {
public void someMethod(ClassOne one) {
System.out.println(one.getClass().getName());
}
}
public class Main {
public static void main(String[] args) {
ClassTwo t = new ClassTwo();
Test tst = new Test();
tst.someMethod(t);
}
}
The output is: ClassTwo
Upvotes: 2