Reputation: 9103
I want to know the method return type from only it's name, i'm using that code but it didn't work for me(it always returns null):
public Object getType(String key) throws Exception {
Object returnType = null;
String name = key;
Method[] methods = name.getClass().getMethods();
for(int i =0; i < methods.length ; i++){
if(key.equals(methods[i])){
returnType = methods[i].getReturnType();
}
}
return returnType;
}
Upvotes: 0
Views: 125
Reputation: 2952
You miss two things. Instead
key.equals(methods[i])
should be:
key.equals(methods[i].getName())
and second thing in my opinion is a class under investigation (your code looks for methods in java.lang.String). So the method should look like:
public Object getType(String methodName, Class<?> clazz) throws Exception {
String name = methodName;
Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++) {
if (name.equals(methods[i].getName())) {
return methods[i].getReturnType();
}
}
return null;
}
and call it like:
type = getType("someMethodName",YourClass.class);
or
type = getType("someMethodName",YourObject.getClass());
Upvotes: 1
Reputation: 200138
Many things are wrong with your attempt; you seem to be arbitrarily chosing methods to invoke, judging intuitively what they do. Please consult the Javadoc of all JDK methods you have never used before.
name.getClass()
returns the object reflecting on java.lang.String
. You need Class.forName(name)
;
your whole scheme cannot possibly work if you don't know what class the method is supposed to be the member of. If your string contains both class name and method name, then you need to parse it to tease these two names apart;
klass.getMethods()
will only give you the public member methods. This may or may not be what you are after. There is also getDeclaredMethods()
, but this one doesn't give you the inherited methods.
Upvotes: 1
Reputation: 16029
Instead of:
if(key.equals(methods[i])){
you should have
if(key.equals(methods[i].getName())){
Also a small improvement can be made in your code, you do not need the returnType
local variable and you do not need to iterate through all the remaining methods when you have already found the method you are looking for, so the code might be:
public Object getType(String key) throws Exception {
String name = key;
Method[] methods = name.getClass().getMethods();
for(int i =0; i < methods.length ; i++){
if(key.equals(methods[i])){
return methods[i].getReturnType();
}
}
return null;
}
Upvotes: 3