下面是内省和类加载器综合使用的一个小程序,希望对大家有所启发
package cn.itcast.text1;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class LoaderToJavaBean {
public static void main(String [] args)throws Exception {
//创建ReflectPoint对象,并赋值
ReflectPoint rf = new ReflectPoint(3,7);
//通过get方法获取属性名称
String propertyName = getPropertyName();
//通过get方法获取属性值
Object retVal = getProperty(rf, propertyName);
System.out.println(retVal);
//通过set方法设置属性值
Object value = 7;
setProperty(rf, propertyName, value);
System.out.println(rf.getX());
}
//设置属性值的方法
private static void setProperty(Object rf, String propertyName,
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
//创建属性描述符对象,将属性名称和加载文件等信息写入其中
PropertyDescriptor pd =
new PropertyDescriptor(propertyName,rf.getClass());
//通过反射的方法类Method,获取属性所对应的set方法
Method methodSetX = pd.getWriteMethod();
methodSetX.invoke(rf, value);
}
//获取属性值的方法
private static Object getProperty(Object rf, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
//创建属性描述符对象,获取属性所对应的名称和加载文件等信息
PropertyDescriptor pd =
new PropertyDescriptor(propertyName,rf.getClass());
//通过反射的方法类Method,获取属性所对应的get方法
Method methodGetX = pd.getReadMethod();
Object retVal = methodGetX.invoke(rf);
return retVal;
}
//获取属性名称的方法
private static String getPropertyName() throws IOException {
//创建读取流对象,将文件中的信息读取到流中
InputStream in =
LoaderToJavaBean.class.getResourceAsStream("config.propert");//这里可以用任何你程序中存在的类加载
//创建Propertie对象,将流中信息加载进内存
Properties props = new Properties();
props.load(in);
in.close();
//获取文件中的属性名称,并作为返回值返回
String propertyName = props.getProperty("propertyName");
return propertyName;
}
}