标签:ade public 指定 oid 代码 关联 and width loader
1 public class User { 2 private String name; 3 private int age; 4 private String address; 5 6 public User(String name, int age, String address) { 7 this.name = name; 8 this.age = age; 9 this.address = address; 10 } 11 12 public String getName() { 13 return name; 14 } 15 16 public void setName(String name) { 17 this.name = name; 18 } 19 20 public int getAge() { 21 return age; 22 } 23 24 public void setAge(int age) { 25 this.age = age; 26 } 27 28 public String getAddress() { 29 return address; 30 } 31 32 public void setAddress(String address) { 33 this.address = address; 34 } 35 36 @Override 37 public String toString() { 38 return "User{" + 39 "name=‘" + name + ‘\‘‘ + 40 ", age=" + age + 41 ", address=‘" + address + ‘\‘‘ + 42 ‘}‘; 43 } 44 }
public interface UserService { void addUser(User user); } public class UserServiceImp implements UserService { @Override public final void addUser(User user) { System.out.println("用户存入数据库成功,数据为:"+user.toString()); } }
public class UserServiceInterceptor implements InvocationHandler { private Object relobj; private static Logger logger=Logger.getLogger(UserServiceInterceptor.class.getName()); public Object getRelobj() { return relobj; } public void setRelobj(Object relobj) { this.relobj = relobj; } public UserServiceInterceptor(Object relobj) { this.relobj = relobj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(args!=null&&args.length>0&&args[0] instanceof User){ User user= (User) args[0]; if(user.getName().length()<=1){ throw new RuntimeException("用户名的长度需要大于1"); } } Object ret=method.invoke(relobj,args); logger.info("操作成功"); return ret; } }
public class Client { public static void main(String[] args) { User user=new User("lhh",10,"北京"); UserService us=new UserServiceImp(); UserServiceInterceptor usi=new UserServiceInterceptor(us); UserService proxy= (UserService) Proxy.newProxyInstance (us.getClass().getClassLoader(),us.getClass().getInterfaces(),usi); proxy.addUser(user); System.out.println(proxy.hashCode()); } }
又是加深学习的一天......
标签:ade public 指定 oid 代码 关联 and width loader
原文地址:https://www.cnblogs.com/limoumou/p/13167021.html