Well I am trying to learn the java MVC pattern, but I can’t understand the following method:
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
}
}
}
I dont’ understand the:
Method method = model.getClass().
getMethod("set"+propertyName, new Class[] {
newValue.getClass()
}
);
So in getMethod we are retrieving the (setSomething) method name according to the property, then the following “thing” is the property value as newValue which is expressed in this fancy expression that I don’t understand at all.
new Class[] <— So it’s an array of classes???
next { newValue.getClass() } <—- OK, getting the class name in brackets by calling the method, but what about the semicolon? There must be some special structure that I don’t understand, it looks like a class, but that must be something different if there’s no semicolon… People explain me what this is please…
This is a bit of an abstract way of coding, and to be honest I’d discourage this way of working if it’s possible to do it otherwise (e.g. by using templates), especially at beginners level. Anyway, I’ll try to explain.
All classes in Java are also objects of the class Class. And all methods are objects of the class Method. You can manipulate these objects like any other objects, by calling their methods and using them as arguments for other methods and so on. That way, you can perfectly instantiate a class by only knowing its name as a String. Same for methods: you can call a method by simply knowing its name as a String.
Now let’s look at your code. Have a quick look at this entry in the Java API for a brief explanation of this part
getMethod("set"+propertyName, new Class[] {newValue.getClass()});.Say you want to call the method
setParameter(int parameterValue) {...}. In that case, we call your method withpropertyNameset to"Parameter"andnewValueset to a certain integer123. Now"set"+propertyNameresults insetParameter, which is the name of our method.newValue.getClass()givesInteger, since that’s what123is.The
getMethodrequires an array of Classes though, because there may exist a number of methods with the same name, but a different number and types of arguments (e.g. there is a chance the methodsetParameter(double parameterValue) {...}exists as well). So we put thatnewValue.getClass()in an array with only one item, by writingnew Class[] {newValue.getClass()}.And there you have it: you retrieve a
Methodobject by callingMethod method = model.getClass(). getMethod("set"+propertyName, new Class[] {newValue.getClass()});and then you call that method using
method.invoke(model, newValue);, which is simply a dynamic way of callingsetParameter(123).