The reflection mechanism is used in dynamic proxies to: obtain metadata of the proxied class, dynamically generate proxy classes, and implement methods for the proxy class. Practical case: Create a dynamic proxy class to intercept the getUser() method of the UserService class, and execute custom logic before and after the method is called.
The reflection mechanism is a set of APIs provided by Java that allow programs to Inspect and modify classes and their members at runtime. It can be achieved through classes in the java.lang.reflect
package:
Class
: Represents a class. Method
: Represents a method in the class. Field
: Represents a field in the class. Dynamic Proxy is a design pattern in Java that allows the creation of objects that can transparently call methods of other objects. The proxy class is created at runtime based on the proxied class, and method calls are made based on the proxy class.
The reflection mechanism plays a vital role in dynamic proxy, which enables the proxy class to:
Class
class to get the class information, methods and fields of the proxied class. Method
class, the proxy class can call the method of the proxy class and execute custom logic before and after the method call. Let us create a dynamic proxy class to intercept the getUser()
method of the UserService
class:
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFactory { public static <T> T createProxy(Class<T> interfaceClass) { return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] {interfaceClass}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 拦截方法调用,并执行自定义逻辑 System.out.println("Method called: " + method.getName()); return method.invoke(new UserService(), args); } }); } } public interface UserService { User getUser(String username); } public class UserServiceImple implements UserService { @Override public User getUser(String username) { // 获取用户信息 return new User(); } } public class Main { public static void main(String[] args) { UserService proxy = ProxyFactory.createProxy(UserService.class); proxy.getUser("admin"); } }
After running this code, the output will be:
Method called: getUser
This output indicates that the proxy class has successfully intercepted and processed the getUser()
method of the UserService
class.
The above is the detailed content of What is the relationship between Java reflection mechanism and dynamic proxy?. For more information, please follow other related articles on the PHP Chinese website!