I've just created method and wrote it to the JAR file, now I want to invoke it and it keeps giving me NoSuchMethodException. What is wrong with the code below? Declarations (global):
private static String newMethodBody="";
private static CtClass ctClass;
private static String newMethodBody="";
private static CtMethod ctMethod;
This is how I create method:
private static void createMethod() throws CannotCompileException, NotFoundException, IOException {
JTextArea JTextArea = new JTextArea(50,50);
StringBuilder sb = new StringBuilder(64);
sb.append(" public static void TestHelloWorld() {\n");
sb.append(" System.out.println(\"New example method\"); } \n");
newMethodBody = sb.toString();
JTextArea.setText(newMethodBody);
String[] options = {"OK"};
int selectedOption = JOptionPane.showOptionDialog(null, JTextArea, null, JOptionPane.NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options , options[0]);
if(selectedOption == 0)
{ try {
newMethodBody = JTextArea.getText();
CtMethod newmethod;
newmethod = CtNewMethod.make(JTextArea.getText(), ctClass);
ctClass.addMethod(newmethod);
ctClass.writeFile();
}
catch(CannotCompileException e) {
JOptionPane.showMessageDialog(null, "Can't compile file");
JOptionPane.showMessageDialog(null, e);
}}}
That's how I want to execute it:
private static void createAndExecuteMethod() throws ClassNotFoundException,InstantiationException, IllegalAccessException,NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, MalformedURLException, NotFoundException
{
File file = new File(path);
URL url = file.toURI().toURL();
URL[] urls = new URL[] { url };
ClassLoader cl = new URLClassLoader(urls);
Class loadedClass = cl.loadClass(ctClass.getName());
Object createdObject = loadedClass.newInstance();
Method method = loadedClass.getDeclaredMethod(ctMethod.getName(), loadedClass);
method.invoke(createdObject);
}
Aucun commentaire:
Enregistrer un commentaire