(2)如果获取的get方法不为空,则通过java反射执行该方法。也就是调用了person中的getName()方法获取值,其实到这里就分析完成了。后面分析一下getGetMethod是怎么获取相应的方法的。
11、getGetMethod()代码:
public static final Method getGetMethod(OgnlContext context, Class targetClass, String propertyName) throws IntrospectionException, OgnlException
{
Method result = null;
PropertyDescriptor pd = getPropertyDescriptor(targetClass, propertyName);
if (pd == null) {
List methods = getDeclaredMethods(targetClass, propertyName, false /* find 'get' methods */);
if (methods != null) {
for (int i = 0, icount = methods.size(); i < icount; i++) {
Method m = (Method)methods.get(i);
Class[] mParameterTypes = getParameterTypes(m);
if (mParameterTypes.length == 0) {
result = m;
break;
}
}
}
} else {
result = pd.getReadMethod();
}
return result;
}
注释:(1)getPropertyDescriptor获取和属性name相关的方法,并且保存到PropertyDescriptor对象中。
PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
<1、getPropertyType(),获得属性的Class对象。
<2、getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法。ognl
<3、hashCode(),获取对象的哈希值。
<4、setReadMethod(MethodreadMethod),设置用于读取属性值的方法;setWriteMethod(MethodwriteMethod),设置用于写入属性值的方法;
(2)PropertyDescriptor获取对象后,如果不为空则调用pd.getReadMethod()方法:
public synchronized Method getReadMethod() {
Method readMethod = getReadMethod0();
if (readMethod == null) {
Class cls = getClass0();
if (cls == null || (readMethodName == null && readMethodRef == null)) {
// The read method was explicitly set to null.
return null;
}
if (readMethodName == null) {
Class type = getPropertyType0();
if (type == boolean.class || type == null) {
readMethodName = "is" + getBaseName();
} else {
readMethodName = "get" + getBaseName();
}
}
// Since there can be multiple write methods but only one getter
// method, find the getter method first so that you know what the
// property type is. For booleans, there can be "is" and "get"
// methods. If an "is" method exists, this is the official
// reader method so look for this one first.
readMethod = Introspector.findMethod(cls, readMethodName, 0);
if (readMethod == null) {
readMethodName = "get" + getBaseName();
readMethod = Introspector.findMethod(cls, readMethodName, 0);
}
try {
setReadMethod(readMethod);
} catch (IntrospectionException ex) {
// fall
}
}
return readMethod;
}
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-32760-9.html
比如小国
你知道美国派多少
烊烊
不知道是什么品牌味道超级难喝零售假要比RIO便宜2元