Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
getter/setter以外のメソッドをJavaBeansのプロパティアクセッサに使う例
package aoetk.sample;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
/**
* Beanの利用例.
*/
public class JavaBeansSampleApp {
public static void main(String[] args) {
try {
Test test = new Test();
BeanInfo testBeanInfo = Introspector.getBeanInfo(test.getClass());
PropertyDescriptor[] propertyDescriptors = testBeanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : propertyDescriptors) {
if ("わーい".equals(pd.getName())) {
System.out.println("わーいプロパティのsetter: " + pd.getWriteMethod());
System.out.println("わーいプロパティのgetter: " + pd.getReadMethod());
pd.getWriteMethod().invoke(test, "なにこれー?");
}
}
System.out.println(test);
} catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
package aoetk.sample;
/**
* getter/setterを使わないJavaBeansの例.
*/
public class Test {
private String わーい;
public String すごーい() {
return わーい;
}
public void たーのしー(String myProperty) {
this.わーい = myProperty;
}
@Override
public String toString() {
return "Test{" +
"わーい='" + わーい + '\'' +
'}';
}
}
package aoetk.sample;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.beans.SimpleBeanInfo;
/**
* {@link Test}のJavaBeans情報.
*/
public class TestBeanInfo extends SimpleBeanInfo {
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
try {
return new PropertyDescriptor[]{
new PropertyDescriptor("わーい", Test.class, "すごーい", "たーのしー")
};
} catch (IntrospectionException e) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment