package de.tutorials.reflection;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class StringReflectionExample {
private static final Map<String, Class> primitiveTypes = new HashMap<String, Class>();
private static final Map<Class, Class> wrapperTypes = new HashMap<Class, Class>();
public static void main(String[] args) {
primitiveTypes.put("int", int.class);
primitiveTypes.put("float", float.class);
primitiveTypes.put("byte", byte.class);
primitiveTypes.put("double", double.class);
primitiveTypes.put("long", long.class);
primitiveTypes.put("boolean", boolean.class);
wrapperTypes.put(int.class, Integer.class);
wrapperTypes.put(float.class, Float.class);
wrapperTypes.put(long.class, Long.class);
wrapperTypes.put(byte.class, Byte.class);
wrapperTypes.put(double.class, Double.class);
wrapperTypes.put(boolean.class, Boolean.class);
String[] paramTypes = { "java.lang.String", "int" };
String[] params = { "test", "3" };
Foo foo = new Foo();
try {
Class[] classes = stringArrayToClassArray(paramTypes);
Object[] objects = getObjectArray(params, classes);
Method method = Foo.class.getMethod("machWas", classes);
method.invoke(foo, objects);
} catch (Exception e) {
e.printStackTrace();
}
}
public static class Foo {
public void machWas(String text, int i) {
System.out.println("Text="+text+" zahl="+i);
}
}
private static Class[] stringArrayToClassArray(String[] classes) {
Class[] clazzes = new Class[classes.length];
for (int i = 0, size = classes.length; i < size; i++) {
clazzes[i] = getClassObject(classes[i]);
}
return clazzes;
}
private static Class getClassObject(String clazz) {
Class c = primitiveTypes.get(clazz);
if (c == null) {
try {
c = Class.forName(clazz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return c;
}
private static Object[] getObjectArray(String[] params, Class[] classes) {
Object[] objects = new Object[params.length];
for (int i = 0, size = params.length; i < size; i++) {
if (classes[i].isPrimitive()) {
objects[i] = parse(params[i], classes[i]);
} else {
objects[i] = classes[i].cast(params[i]);
}
}
return objects;
}
private static Object parse(String param, Class clazz) {
Class wrapperClass = wrapperTypes.get(clazz);
Method[] methods = wrapperClass.getMethods();
for (int i = 0, size = methods.length; i < size; i++) {
Method method = methods[i];
Class<?>[] parameterTypes = method.getParameterTypes();
if (method.getName().startsWith("parse")
&& parameterTypes.length == 1
&& parameterTypes[0].equals(String.class)) {
try {
return method.invoke(null, new Object[] { param });
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
}