lundi 2 mars 2015

Java reflection calling method "getDeclaredConstructors"

I didn't really know how to put the title of the question. Basically i'm trying to do some tricky stuff with the java reflect api. Here's what im trying to do:



import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, InstantiationException {
Scanner in = new Scanner(System.in);
String className = in.nextLine();
Class c = Class.forName(className);
Object myObj = c.newInstance();
Method m = c.getMethod("getDeclaredConstructors");
Object retn = m.invoke(myObj);
System.out.println(retn);
in.close();
}
}


I'm testing this with the input: java.lang.String I always get as output:



Exception in thread "main" java.lang.NoSuchMethodException: java.lang.String.getDeclaredConstructors()
at java.lang.Class.getMethod(Class.java:1778)
at Test.main(Test.java:15)


I understand that the method "getDeclaredConstructors()" is from the class Class.


Can someone please tell me what am i doing wrong here? What i was expecting was a list of the declared constructors for the class name i gave as input, in this case: java.lang.String


EDIT: I should have detailed more my problem. I know that i could execute c.getDeclaredConstructors(), but thats not the case.


This is only a small part of the program i want to build. In the final version, the user will provide as input a name of a class, say "java.lang.String" and then it will provide generic methods that he wishes to apply to that class. So the user would enter "getDeclaredConstructors" and i would have to apply the method with that name to the class "java.lang.String".


Im only doing this to understand how exactly i can achive that.






Aucun commentaire:

Enregistrer un commentaire