code manipulation : dynamic proxy

This commit is contained in:
haerong22
2021-02-21 22:48:14 +09:00
parent edc5bf337b
commit da7847a43d
4 changed files with 33 additions and 1 deletions

View File

@@ -3,4 +3,6 @@ package org.example.proxy;
public interface BookService {
void rent(Book book);
void returnBook(Book book);
}

View File

@@ -14,4 +14,9 @@ public class BookServiceProxy implements BookService {
bookService.rent(book);
System.out.println("다른기능!!");
}
@Override
public void returnBook(Book book) {
}
}

View File

@@ -6,4 +6,9 @@ public class DefaultBookService implements BookService{
public void rent(Book book) {
System.out.println("rent: " + book.getTitle());
}
@Override
public void returnBook(Book book) {
System.out.println("return: " + book.getTitle());
}
}

View File

@@ -2,9 +2,28 @@ package org.example.proxy;
import org.junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class BookServiceTest {
BookService bookService = new BookServiceProxy(new DefaultBookService());
// BookService bookService = new BookServiceProxy(new DefaultBookService());
BookService bookService = (BookService) Proxy.newProxyInstance(
BookService.class.getClassLoader(), new Class[]{BookService.class},
new InvocationHandler() {
BookService bookService = new DefaultBookService();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("rent")) {
System.out.println("로깅!!");
Object invoke = method.invoke(bookService, args);
System.out.println("다른기능!!");
return invoke;
}
return method.invoke(bookService, args);
}
});
@Test
public void proxy() {
@@ -13,5 +32,6 @@ public class BookServiceTest {
book.setTitle("spring");
bookService.rent(book);
bookService.returnBook(book);
}
}