vendredi 23 janvier 2015

Reflection. Execution constructor

I need to execute some method via reflection


method to execute



public void someMethod(int value1, int value2, String str, int value3)
{
try
{
// some code
}
catch (Exception e)
{
e.printStackTrace();
}
}


This is execution code



public static void execute()
{
try
{
String className = "some.class";
String classPath = "some.pack.name" + ":" + "some.class";
PathClassLoader loader = new dalvik.system.PathClassLoader(classPath, ClassLoader.getSystemClassLoader());

Class clazz = Class.forName(className, true, loader);
Method method = clazz.getDeclaredMethod("someMethod", Integer.TYPE, Integer.TYPE, String.class, Integer.TYPE);
Object object = clazz.newInstance();

method.invoke(object, 1, 2, "str", 3);
}
catch (Throwable e) {e.printStackTrace();}
}


But I gets error



java.lang.InstantiationException: can't instantiate class someClass; no empty constructor
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)


After that I espected constructors for someClass and got this



someClass(android.content.Context,com.android.internal.someClass)
GenericParameterType 0 - class android.content.Context
GenericParameterType 1 - interface com.android.internal.someClass


The question is: how to execute someMethod with given parameters and given generic types?






Aucun commentaire:

Enregistrer un commentaire