下面是內省和類加載器綜合使用的一個小程序,希望對大家有所啓發
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;
}
}