我正在尝试学习 java MVC 模式,但我无法理解以下方法:
protected void setModelProperty(String propertyName, Object newValue) {
for (AbstractModel model: registeredModels) {
try {
Method method = model.getClass().
getMethod("set"+propertyName, new Class[] {
newValue.getClass()
}
);
method.invoke(model, newValue);
} catch (Exception ex) {
// Handle exception
}
}
}
我不明白:
Method method = model.getClass().
getMethod("set"+propertyName, new Class[] {
newValue.getClass()
}
);
因此,在 getMethod 中,我们根据属性检索 (setSomething) 方法名称,然后下面的“thing”就是属性值 newValue,它用这个我根本不理解的奇特表达式来表示。
new Class[]
<--- 所以它是一个类数组???
next { newValue.getClass() }
<---- 好的,通过调用方法获取括号中的类名,但是分号呢?一定有一些我不明白的特殊结构,它看起来像一个类,但如果没有分号,那一定是不同的东西......请人们解释一下这是什么......
最佳答案
随着:
new Class[] { newValue.getClass() }
您正在指定内联类的数组,并将其传递给 getMethod 的参数。
由于混合了“Class”,这可能会更令人困惑,但它与以下内容一样有效:
Integer[] bla = new Integer[]{1,2,3,4};
getMethod 接收您在类中查找的方法的名称作为参数,以及指定所述方法的参数的类数组。示例:
getMethod("setValues", new Class[]{String.class, Integer.class}
将寻找类似的方法:
public Something setValues(String p1, Integer p2)
即使它存在于同一个类中,它也不会匹配,例如:
public Something setValues(String p1)
或任何其他变体。
关于java - MVC( Model View Controller );请解释一下这个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10026520/