JAva反射メカニズム(メモ)
9955 ワード
JAva反射メカニズムはclassを取得する相応の方法である
たとえば、コンストラクション関数を取得します.
テンプレート:
反射関数テンプレート:
反射mainメソッド
取得フィールド:
例:
たとえば、コンストラクション関数を取得します.
テンプレート:
Class test = Class.forName("cn.test.Person");// class
Constructor test1 = test.getConstructor(null); //
Person person = (Person) test1.newInstance(null);//new
// ,
Constructor c3 = test3.getDeclaredConstructor(List.class);//
c3.setAccessible(true);//
反射関数テンプレート:
//
Class classtest = Class.forName("");
Method method = classtest.getMethod(" ", );//
method.invoke( , );// ,
反射mainメソッド
Class testmain = Class.forName("cn.test.Person");//
Method tt = testmain.getMethod("main",String[].class);// main
tt.invoke(null, new Object[]{new String[]{"aa","bbb"}});//
取得フィールド:
Person person = new Person("yy");
Class cla = Class.forName("cn.test.Person");
Field field = cla.getField("name");// name
String name = (String) field.get(person);
System.out.println(name);
例:
//Person
package cn.test;
import static java.lang.System.out;
import java.awt.List;
public class Person {
private String name;
public Person(){
out.print("nulllllllll");
}
public Person(String name){
out.println(name);
this.name = name;
}
public Person(String name,int n){
out.print(""+name+" "+n);
}
private Person(List l){
out.print("static person");
}
public void getint(int x){
System.out.println("x=="+x);
}
public static void main(String[] args){
System.out.print("main ");
}
}
//
package cn.test.test;
import java.awt.List;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Test;
import cn.test.Person;
public class test {
@Test
public void test1() throws Exception{
Class test = Class.forName("cn.test.Person");
Constructor test1 = test.getConstructor(null);
Person person = (Person) test1.newInstance(null);
}
@Test
public void test2() throws Exception{
Class test2 = Class.forName("cn.test.Person");
Constructor c2 = test2.getConstructor(String.class);
Person person = (Person) c2.newInstance("xxvdfdfd");
}
@Test
public void test3() throws Exception{
Class test3 = Class.forName("cn.test.Person");
Constructor c3 = test3.getDeclaredConstructor(List.class);
c3.setAccessible(true);
Person person = (Person) c3.newInstance(new List());
}
//
@Test
public void test4() throws Exception{
Person person = new Person();
Class test4 = Class.forName("cn.test.Person");
Method tt = test4.getMethod("getint", int.class);
tt.invoke(person, 12);
}
//
@Test
public void testmain() throws Exception{
Class testmain = Class.forName("cn.test.Person");
Method tt = testmain.getMethod("main",String[].class);
tt.invoke(null, new Object[]{new String[]{"aa","bbb"}});
}
//
@Test
public void getname() throws Exception{
Person person = new Person("yy");
Class cla = Class.forName("cn.test.Person");
Field field = cla.getField("name");// name
String name = (String) field.get(person);
System.out.println(name);
}
}