Call a method when class name not known at compile time
I have a number of sub-games, SubGame1, SubGame2 etc. Each is derived from a SubGame class and implements a static String getDescription() function.
I want to access these descriptions, e.g. SubGame1.getDescription(), SubGame2.getDescription() etc.
However I want to use a code loop and not all the subgames will exist.
How can I call getDescription() for a sub game when I only know the game number. Something like:
St开发者_高级运维ring description = Class.forName(this.getPackageName()+".SubGame"+subGameNo.getDescription();
but that returns: The method getDescription() is undefined for the type Class< capture#5-of ?>
Any ideas?
You can call it, but you have to do it via the java.lang.reflect
classes. Class.forName
gives you a Class
instance. You then call getMethod
to get the Method
, on which you can then call invoke
.
Off the top of my head:
Class cls;
Method getDescription;
String description;
cls = Class.forName(this.getPackageName() + ".SubGame" + subGameNo);
getDescription = cls.getMethod("getDescription");
description = getDescription.invoke(null);
...but you may have to play with the args a bit.
You can use Class.forName() to get the instance of the class.
Then you can call the method using reflection. Code would look something like this
Class<?> clazz = Class.forName(this.getPackageName()+".SubGame"+subGameNo);
Method descriptionMethod = clazz.getMethod("getDescription", new Class[] {});
String value = (String) descriptionMethod .invoke(this, new Object[] {});
You could just create a Map of game numbers to game descriptions (map.put(1, SubGame1.getDescription()
) and then just grab the description from the map as needed. It's not as dynamic as you may want but it will work.
精彩评论