package Demo1; import java.io.InputStream; import java.util.List; //被反射类 public class person { public String name="li liangliang"; public person() { System.out.print("my name is person"); } public person(String name,int age) { System.out.println("name="+ name+" age="+age); } private person(String name) { System.out.print(name); } public void aal() { System.out.println("aal"); } public void aal(String name,int password) { System.out.print(name+":"+"password"+password); } public Class[] aal(String name,int[] password) { return new Class[]{String.class}; } private void aal(InputStream in) { System.out.print(in); } public static void aal(int num) { System.out.println(num); } }
反射
package Demo1; import static org.junit.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.junit.Test; public class Demo1TestTest { //反射public void aal() @Test public void Test1()throws Exception{ person p=new person(); Class clazz=Class.forName("Demo1.person"); Method method=clazz.getMethod("aal", null); method.invoke(p,null); } //反射public void aal(String name,int password) public void Test2()throws Exception{ person p=new person(); Class clazz=Class.forName("Demo1.person"); Method method=clazz.getMethod("aal",String.class,int.class); method.invoke(p,"liang",22); } public void Test3()throws Exception{ person p=new person(); Class clazz=Class.forName("Demo1.person"); Method method=clazz.getMethod("aal",String.class,int[].class); Class cs[]=(Class[]) method.invoke(p,"liang",new int[]{1,2,3,4}); System.out.print(cs[0]); } }
package Demo1; import static org.junit.Assert.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import org.junit.Test; import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List; public class Demo2Test { @Test public void test() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class clazz=Class.forName("Demo1.person"); Constructor c=clazz.getConstructor(null); person p=(person)c.newInstance(null); System.out.print(p.name); } @Test public void Test1()throws Exception{ Class clazz=Class.forName("Demo1.person"); Constructor c=clazz.getConstructor(String.class); person p=(person) c.newInstance("xxxxx"); } @Test public void Test()throws Exception{ Class clazz=Class.forName("Demo1.person"); Constructor c=clazz.getConstructor(String.class,int.class); person p=(person) c.newInstance("int",11); } @Test public void Test4()throws Exception{ Class clazz=Class.forName("Demo1.person"); Constructor c=clazz.getDeclaredConstructor(String.class); c.setAccessible(true); person p=(person)c.newInstance("abc"); } @Test public void Test5()throws Exception{ Class clazz=Class.forName("Demo1.person"); person p=(person)clazz.newInstance(); } }