Effective.Enterprise
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.logging.Logger;
public class LoggingProxy implements InvocationHandler {
private Logger logger;
private Object proxiedObject;
private LoggingProxy(Logger l, Object obj) {
// TODO Auto-generated constructor stub
logger = l;
proxiedObject = obj;
}
public static Object newLoggingProxyAround(Logger logger, Object obj) {
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
.getClass().getInterfaces(), new LoggingProxy(logger, obj));
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
Object result;
try {
logger.info("Entering method " + m.getName());
result = m.invoke(proxiedObject, args);
} catch (Exception x) {
logger.warning("unexpected Exception " + x + " invoke "
+ m.getName());
throw x;
} finally {
logger.info("Exiting mothod " + m.getName());
}
return result;
}
}
//-----------
public interface Person {
public String getFirstName();
public void setFirstName(String value);
public String getLastName();
public void setLastName(String value);
public int getAge();
public void setAge(int value);
}
//--------------------
public class PersonImpl implements Person {
private String firstName;
private String lastName;
private int age;
public int getAge() {
// TODO Auto-generated method stub
return this.age;
}
public String getFirstName() {
// TODO Auto-generated method stub
return this.firstName;
}
public String getLastName() {
// TODO Auto-generated method stub
return this.lastName;
}
public void setAge(int value) {
// TODO Auto-generated method stub
this.age=value;
}
public void setFirstName(String value) {
// TODO Auto-generated method stub
this.firstName=value;
}
public void setLastName(String value) {
// TODO Auto-generated method stub
this.lastName=value;
}
}
//------------
import java.util.logging.Logger;
public class PersonManager {
public Logger personLogger= Logger.getLogger("Person", "a");
public boolean loggerEnabled=false;
/**
* @param args
*/
public Person getperson(String firstName, String lastName){
Person p=new PersonImpl();
if(loggerEnabled){
p=(Person)LoggingProxy.newLoggingProxyAround(personLogger, p);
}
p.setFirstName(firstName);
p.setLastName(lastName);
return p;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PersonManager pm=new PersonManager();
pm.loggerEnabled=true;
System.out.println("-----------");
Person p=pm.getperson("firstName", "lastName");
// System.out.println(p.getFirstName()+"."+p.getLastName());
}
}