javase-反射方法学习记录

来源:互联网 发布:python 驼峰转 编辑:程序博客网 时间:2024/05/22 13:26
public class Demo3 {
//反射类的方法 public void test1()
@SuppressWarnings("unchecked")
@Test
public void test1() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException{
Class clazz =Class.forName("cn.reflect.Person");
Method method =clazz.getMethod("test1", null);
method.invoke(clazz.newInstance(), null);
}
//public void test1(String name,int password)
@Test
public void test2() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException{
Class clazz =Class.forName("cn.reflect.Person");
Method method =clazz.getMethod("test1",String.class,int.class);
method.invoke(clazz.newInstance(),"李四",1234);
}

//public Class[] test1(String name,int[] password)
@Test
public void test3() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException{
Class clazz =Class.forName("cn.reflect.Person");
Method method =clazz.getMethod("test1",String.class,int[].class);
Class cs[]=(Class[]) method.invoke(clazz.newInstance(),"王五",new int[]{1,23});
System.out.println(cs[0]);

}
//private void test1(InputStream in)
@Test
public void test4() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, FileNotFoundException{
Class clazz =Class.forName("cn.reflect.Person");
Method method =clazz.getDeclaredMethod("test1", InputStream.class);
method.setAccessible(true);//暴力编译
method.invoke(clazz.newInstance(),new FileInputStream("d:\\1.mp4"));

}
//public static void test1(int num)
@Test
public void test5() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, FileNotFoundException{
Class clazz =Class.forName("cn.reflect.Person");
Method method =clazz.getMethod("test1", int.class);
//静态方法不用对象
method.invoke(null,23);
}
//public static void main(String[] args)
@Test
public void test6() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, FileNotFoundException{
Class clazz =Class.forName("cn.reflect.Person");
Method method =clazz.getMethod("main",String[].class);

//method.invoke(null,new Object[]{new String[]{"2","3"}});
 
method.invoke(null, (Object)new String[]{"aa","bb"});
}
}
0 0
原创粉丝点击