2013/11/21

java reflect constructor ect

★引数なし
Class<String> clazz = String.class;
String obj=clazz.newInstance();

★引数ある、Constructorを使う。配列も必要!
Class<Integer> clazz = Integer.class;
Class<?>[] types = { int.class };

Constructor<Integer> constructor= clazz.getConstructor(types);
Object[] args = { Integer.valueOf(123) };
Integer obj = constructor.newInstance(args);

★clazz = Class.forName("java.lang.String");

★ClassLoader!!!
ClassLoader loader = Thread.currentThread().getContextClassLoader();
ClassLoader loader = ClassLoader.getSystemClassLoader()
ClassLoader loader = URLClassLoader.newInstance(new URL[]{ new File("jarファイル").toURI().toURL() });
clazz = loader.loadClass("java.lang.String");

★method
Method method =  clazz.getMethod("メソッド名", null);
Object ret = method.invoke(null, null);

Method method =  clazz.getMethod("メソッド名", new Class[]{ int.class });
Object ret = method.invoke(object, new Object[]{ new Integer(1) });

★Field
Class c = obj.getClass();
Field f = c.getField("field");
f.set(obj, 123);