java 代码
- public class ReflectionFiledPrintTest {
- private String name = "GoGoGo";
- private String city = "DoDoDo";
- public String getCity() {
- return city;
- }
- public void setCity(String city) {
- this.city = city;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public static void main(String args[]) {
- Object obj = "222";
- System.out.println("111"+obj);
- ReflectionFiledPrintTest tfpt = new ReflectionFiledPrintTest();
- try {
- Class reClass = Class
- .forName("reflection.ReflectionFiledPrintTest");
- Method methods[] = reClass.getDeclaredMethods();
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().startsWith("get")) {
- Object retobj = methods[i].invoke(tfpt, null);
- System.out.println(methods[i].getName() + "="
- + (String) retobj);
- }
- }
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- }
- }
Java反射机制示例
本文通过一个Java类的实例展示了如何使用Java反射机制获取并打印类的所有getter方法返回的属性值。该示例代码首先创建了一个ReflectionFiledPrintTest类的对象,并通过反射获取了该类及其父类的所有方法,然后筛选出所有以get开头的方法并调用它们来获取并打印对应的属性值。
2174

被折叠的 条评论
为什么被折叠?



