---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
JavaBean——>特殊的Java类
class Person
{
private int x;//我们看不见
public int getAge(){ //得到age,age是javabean的属性名
return x;
}
public void setAge(int age){ //设置age
this.x = age;
}
}
符合这种规则的类叫JavaBean
使用JavaBean的好处:
1,在JavaEE开发中,经常要使用到JavaBean。很多环境都要求按javaBean方式进行操作,别人都这么做,我们也就得跟着这么做。
2,JDK中提供了对JavaBean进行操作的一些API,这套API就称为内省。如果要自己去通过getX方法来访问私有的x,有一定难度,用内省这套API操作JavaBean比用普通类的方式更方便。
Age——>如果第二个字母是小的,则把第一个字母变成小的——>age
例如:
gettime——>time
setTime——>time
getCPU——>CPU
JavaBean的简单内省操作:
例子:
ReflectPoint.class:
public class ReflectPoint {
private int x;
public int y;
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
IntroSpectorTest.class
package reflection;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class IntroSpectorTest {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
ReflectPoint pt1 = new ReflectPoint(3,5);
String propertyName = "x"; //属性名
//"x"-->"X"-->"getX"-->MethodGetX-->
Object retVal = getProperty(pt1, propertyName); //方法调用方法(对象名,属性名)返回值
System.out.println(retVal);
Object value = 7;
setProperties(pt1, propertyName, value);//没有返回值
System.out.println(pt1.getX());
}
private static void setProperties(Object pt1, String propertyName, //数据源——重构——抽取方法
Object value) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodSetX = pd2.getWriteMethod();
methodSetX.invoke(pt1, value);
}
private static Object getProperty(Object pt1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());//获取属性描述对象pd
Method methodGetX = pd.getReadMethod(); //反射取方法名
Object retVal = methodGetX.invoke(pt1);
/* BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass()); //复杂的方法
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = null;
for(PropertyDescriptor pd : pds){
if(pd.getName().equals(propertyName))
{
Method methodGetX = pd.getReadMethod();
retVal = methodGetX.invoke(pt1);
break;
}
}
*/
return retVal;
}
}
小结:内省应该就是在软件内便捷的编写程序~
---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------详细请查看:http://edu.youkuaiyun.com