dear every one
i get a class User like thisi want to add a new method to user through Aspect,so i do like thisCode:package com.yyhy.java.Privilege;// TODO define package import javax.persistence.*; import java.util.*; @Entity @Table( name="USER") public class User { //Attributes private Long userID; private String userName; private String passWord; private String remark; //Getters and Setters @Id @Column(name="USERID",nullable=false) public Long getUserID() { return this.userID; } public void setUserID(Long UserID) { this.userID=UserID; } @Column(name="USERNAME",nullable=false) public String getUserName() { return this.userName; } public void setUserName(String UserName) { this.userName=UserName; } @Column(name="PASSWORD",nullable=false) public String getPassWord() { return this.passWord; } public void setPassWord(String PassWord) { this.passWord=PassWord; } @Column(name="REMARK") public String getRemark() { return this.remark; } public void setRemark(String ReMark) { this.remark=ReMark; } @Override public String toString() { // TODO Auto-generated method stub return this.userName+this.remark; } }
Code:package com.yyhy.java.search.compass; public interface Compassable { public String getContent(); }Code:package com.yyhy.java.search.compass; public class DefaultCompassableImpl implements Compassable { @Override public String getContent() { return this.toString();//here is error,i want to use User.toString } }this is my configCode:package com.yyhy.java.search.compass; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; @Aspect public class CompassableAspect {//com.yyhy.hx.*+ @DeclareParents(value="com.yyhy.java.Privilege.User", defaultImpl=DefaultCompassableImpl.class) public static Compassable compassable; }
My test codeCode:<aop:aspectj-autoproxy /> <bean id="CompassAspect" class="com.yyhy.java.search.compass.CompassableAspect" > </bean> <bean id="User" class="com.yyhy.java.Privilege.User"/>
the result are:Code:import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import com.yyhy.java.Privilege.User; import com.yyhy.java.search.compass.Compassable; public class testAspectj { public static void main(String[] arg) { FileSystemResource resource = new FileSystemResource("E:\\javawork\\hxCode\\src\\applicationContext.xml"); XmlBeanFactory beanFactory = new XmlBeanFactory(resource); User user = (User)beanFactory.getBean("User"); user.setUserName("aaa"); System.out.println(user.toString()); System.out.println(user.getContent()); Compassable a=(Compassable)user; System.out.println(a.getContent()); } }
aaanull
com.yyhy.java.search.compass.DefaultCompassableImp l@1128f5a
com.yyhy.java.search.compass.DefaultCompassableImp l@1128f5a
i want the user.getContent() returns the same as user.toString()
what can i do?
thanks alot


Reply With Quote
