/**
*
*/
package com.reflection;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Test;
/**
* @author lihai
* @createdtime 2018-5-8 下午11:11:51
* @类描述
*/
public class RefDemo {
@Test
public void getMethodClass() throws InstantiationException,
IllegalAccessException, SecurityException, NoSuchMethodException,
IllegalArgumentException, InvocationTargetException{
//
Class<?> c = methodClass.class;
Object object1 = c.newInstance();//使用Class对象的newInstance()方法来创建Class对象对应类的实例
//getMethods()方法返回类的所有公用方法,包括其继承类的公用的方法
//Method[] methods = c.getMethods();
//getDeclaredMethods()方法返回类或接口声明的所有方法,包括公共,保护,默认访问和私有方法,不包括继承的方法
//Method[] declareMethods = c.getDeclaredMethods();
//获取methodClass类的add方法
Method method = c.getMethod("add", int.class,int.class);
Object result = method.invoke(object1, 1,5);
System.out.println(result);
/*for(Method method2 : methods){
System.out.println(method2);
}
System.out.println("-------------------------------------------------------------");
for(Method method2 : declareMethods){
System.out.println(method2);
}*/
}
/**
* 利用反射创建数组
* @throws ClassNotFoundException
*/
@Test
public void createArrayByRef() throws ClassNotFoundException{
Class<?> class1 = Class.forName("java.lang.String");
Object array = Array.newInstance(class1, 25);
Array.set(array, 0, "ttt");
Array.set(array, 1, "rrr");
Array.set(array, 2, "eee");
Array.set(array, 3, "www");
Array.set(array, 4, "qqq");
System.out.println(Array.get(array, 3));
}
}
class methodClass{
public final int juce=3;
public int add(int a,int b){
return a+b;
}
public int sub(int a,int b){
return a+b;
}
}
反射的简单用例--1
最新推荐文章于 2022-08-06 11:23:35 发布