Created
April 26, 2017 13:20
-
-
Save aoetk/e5a09f67f2ebbc206d0770b21116b69e to your computer and use it in GitHub Desktop.
getter/setter以外のメソッドをJavaBeansのプロパティアクセッサに使う例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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{" + | |
"わーい='" + わーい + '\'' + | |
'}'; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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