在這裏羅列出兩種編寫反射的代碼,我的認爲方式2的書寫更爲簡潔,也更爲直觀。java
EntityInterface.javaide
package com.me.Entity; public interface EntityInterface { public void setName(String name); public String getName(); public int getAge(); public void setAge(int age); }
Entity.javathis
package com.me.Entity; public class Entity implements EntityInterface{ private String name; private int age; public Entity(){ } public Entity(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Entity other = (Entity) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Entity [name=" + name + ", age=" + age + "]"; } }
ClassInstance.javaspa
package net.test.test; import java.lang.reflect.InvocationTargetException; import com.me.Entity.EntityInterface; public class ClassInstance { // 方式1 public void reflection1() { try { Class<?> c = Class.forName("com.me.Entity.Entity"); Object obj = c.newInstance(); c.getMethod("setName", String.class).invoke(obj, "name"); System.out.println(c.getMethod("getName").invoke(obj)); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 方式2 public void reflection2() { try { Class<?> c = Class.forName("com.me.Entity.Entity"); EntityInterface e = (EntityInterface) c.newInstance(); e.setName("name"); System.out.println(e.getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { new ClassInstance().reflection1(); new ClassInstance().reflection2(); } }