probleme invoquer une methode
Bonjour,
Je souhaite utiliser la reflection mais lorsque j' execute j obtiens cette erreur.
Code:
1 2 3 4 5 6
|
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at reflection.Reflection2.isValid(Reflection2.java:37)
at reflection.Reflection2.main(Reflection2.java:60) |
Voici le code de la classe personne:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
package test;
public class Personne{
private Personne(){
}
public Personne getInstance(){
return new Personne();
}
boolean isApte(int age){
if(age >10 & age < 20){
return true;
}else{
return false;
}
}
} |
Voici le code de la reflection
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
package reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import test.Personne;
public class Reflection2 {
public boolean isValid(int age) {
Class[] parameterTypes = new Class[] {Integer.TYPE};
boolean result = false;
Personne newInstance = null;
try {
Method method = Personne.class.getDeclaredMethod("isApte", parameterTypes);
Constructor c = Personne.class.getDeclaredConstructor();
c.setAccessible(true); // solution
try {
newInstance = (Personne) c.newInstance();
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
result = (Boolean) method.invoke(newInstance,new Integer(age));
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
Reflection2 reflection = new Reflection2();
reflection.isValid(5);
}
} |
Je vous rermercie de votre aide