import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ReflectPO { private String h1; private String h2; public String getH1() { return h1; } public void setH1(String h1) { this.h1 = h1; } public String getH2() { return h2; } public void setH2(String h2) { this.h2 = h2; } @Override public String toString() { return "ReflectPO{" + "h1='" + h1 + '\'' + ", h2='" + h2 + '\'' + '}'; } public static void main(String[] args) { try { ReflectPO rp= (ReflectPO)Class.forName("com.takesensors.test.ReflectPO").newInstance(); for (int i = 1; i <=2; i++) { Method method = rp.getClass().getMethod("setH"+i, String.class); method.invoke(rp, "第"+i+"个小时值"); //给方法参数赋值 } System.out.println(rp); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
java 通过反射创建对象并给属性赋值
最新推荐文章于 2024-10-12 21:58:56 发布