As you can see I clearly have a getter for property 'name' in class TemplateVars. A similar piece of code works elsewhere in the system. So why is the following code throwing the following exception?
Code
public class Main {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
String template = "Hello. My name is %%name%% %%surname%% %%contact.email%%";
Pattern pattern = Pattern.compile("%%(.*?)%%");
Matcher matcher = pattern.matcher(template);
TemplateVars item = new TemplateVars();
while (matcher.find()) {
String placeHolder = matcher.group(1);
String value;
if(placeHolder.contains(".")){
value = PropertyUtils.getNestedProperty(item, placeHolder).toString();
}else{
value = PropertyUtils.getProperty(item,placeHolder).toString();
}
template = template.replace("%%" + placeHolder + "%%", value);
}
System.out.println(template);
}
}
class TemplateVars {
private String name = "Boo";
private String surname = "Foo";
private Contact contact;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
}
class Contact {
private String email = "[email protected]";
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Exception
Exception in thread "main" java.lang.NoSuchMethodException: Property 'name' has no getter method in class 'class TemplateVars'
at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1274)
at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:808)
at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:884)
at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:464)
at Main.main(Main.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
The piece of code that I have posted above is only to serve as proof of concept.
This is simply because your classes TemplateVars
and Contact
have the package-local access modifier and PropertyUtils
can not gain access to them.
To solve it make them top classes (i.e. public), or public static inner classes of Main
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With