本帖最后由 思维 于 2014-8-24 17:15 编辑
那天看张老师讲JavaBean那节,有这么几行代码,请问下面的类算JavaBean吗?- import java.lang.reflect.*;
- import java.beans.*;
- class ReflectPoint{
- private int x;
- private int y;
- public ReflectPoint(int x,int y){
- 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;
- }
- }
- class IntroSpectorTest{
- public static void main(String[] args)throws Exception{
- ReflectPoint pt1=new ReflectPoint(3,5);
- String propertyName="x";
- Object retVal=getProperty(pt1,propertyName);
- System.out.println(retVal);
- Object value = 7;
- setProperty(pt1,propertyName,value);
- System.out.println(pt1.getX());
- }
- private static Object getProperty(Object pt1,
- String propertyName)throws Exception{
- /*第一种方式:
- PropertyDescriptor pd1 =
- new PropertyDescriptor(propertyName,pt1.getClass());
- Method getMethodX = pd1.getReadMethod();
- Object retVal = getMethodX.invoke(pt1);
- return retVal;*/
- /*第二种方式:*/
- BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
- PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
- Object retVal = null;
- for(PropertyDescriptor pd : pds){
- if(pd.getName().equals(propertyName)){
- Method getMethodX = pd.getReadMethod();
- retVal = getMethodX.invoke(pt1);
- break;
- }
- }
- return retVal;
- }
- private static void setProperty(Object pt1,
- String propertyName,Object value)throws Exception{
- PropertyDescriptor pd2 =
- new PropertyDescriptor(propertyName,pt1.getClass());
- Method methodSetX = pd2.getWriteMethod();
- methodSetX.invoke(pt1,value);
- }
- }
复制代码 |
|