getClass().getMethod("name", unknown)
For a really abstract application I am creating, I need to call methods without knowing their parameter types and only knowing the parameters开发者_如何学Go in a String shape.
Let say I have the method;
getNames(String like, int amount);
and I have a array of strings containing the 2 parameters, so lets say I have;
String[] params = new String[] {"jack", "25"};
Is there any way that I can get and invoke this method using the params array?
You could try
String[] params = new String[] {"jack", "25"};
Object[] realParams = new Object[params.length];
Method[] methods = getClass().getMethods();
for (Method method : methods) {
if (method.getParameterTypes().length == params.length) {
for (int i = 0; i < method.getParameterTypes().length; i ++) {
Class<?> paramClass = method.getParameterTypes()[i];
if (paramClass = String.class) {
realParams.add(param);
} else if (paramClass == Integer.class || paramClass == Integer.TYPE) {
realParams.add(Integer.parseInt(param));
} else if (other primitive wrappers) {
...
} else {
realParams.add(null); // can't create a random object based on just string
// you can have some object factory here, or use ObjectInputStream
}
}
break; // you can continue here if the parameters weren't converted successfully,
//to attempt another method with the same arguments count.
}
}
Sounds like metaprogramming. You may want to look into Groovy/Scala if you're set on the JVM platform.
Look into the Java reflection APIs, they should (though I don't remember for sure) be able to give you the information you need to ascertain the different types of parameters. You'd then have to iterate over the list and intelligently cast each one based on what the reflection API has told you about the method.
For dynamic programming use a dynamic programming language. Java is not well suited for that kind of stuff.
Have a look at the reflection API anyway, but if you plan to do a lot of programming like that for your application consider other alternatives.
精彩评论