Question:
What is dynamic proxy based on?
Knowledge:
- Java is a statically strongly typed language, but it also has some dynamically typed language capabilities because it provides mechanisms like reflection.
- Proxy pattern: Definition: an object is provided with a proxy object and the proxy object controls access to the original object. That is, the client does not directly control the original object, but indirectly controls the original object through the proxy object. (Similar to real estate agents often seen in Shanghai)
Static proxy mode code:
public class ProxyDemo {
public static void main(String args[]){
RealSubject subject = new RealSubject();
Proxy p = new Proxy(subject);
p.request();
}
}
interface Subject{
void request();
}
class RealSubject implements Subject{
public void request(){
System.out.println("request");
}
}
class Proxy implements Subject{
private Subject subject;
public Proxy(Subject subject){
this.subject = subject;
}
public void request(){
System.out.println("PreProcess");
subject.request();
System.out.println("PostProcess"); }}Copy the code
- Reflection: Java reflection allows you to know all the properties and methods of any class at runtime. For any object, you can call any of its methods and properties. This ability to dynamically retrieve information and invoke methods on objects is called Java’s reflection mechanism. An important part of the reflection mechanism is the “runtime”, which allows us to load, explore, and use.class files that are completely unknown at compile time while the program is running. In other words, a Java program can load a.class file whose name is not known until runtime, then learn of its complete construction and generate its object entities, or set values for its fields, or call its methods. Specific can consult: Java reflection 1 | advanced essential
Runtime annotations use reflection to affect performance; compile-time annotations do not affect performance. Using annotations to declare subscription methods is slower than 2.x. By introducing an annotation processor to index subscription methods during compilation, performance is significantly improved.
According to the official notes, the introduction of annotations made EventBus 3.0 3-5 times worse than 2.x performance, but the introduction of indexes improved EventBus 3.0 at least 3 times better than 2.x performance.
For details, see EventBus 3.0 Best Practices and Principles
- Dynamic proxy: Provides a proxy for other objects to control access to that object. In some cases, an object does not fit or directly reference another object, and a proxy object can act as an intermediary between the two. The run-time specifies which object to proide. Constituent elements:
- Abstract class interface
- Proxied classes (classes that concretely implement an abstract class interface)
- Dynamic proxy classes that actually invoke methods and properties of the proxied class
Implementation – [X] JDK itself provides dynamic proxy, is the main use of reflection mechanism
/ / retrofit2 Retrofit is use to the public in source code < T > T create (final Class < T > service) {Utils. ValidateServiceInterface (service);if (validateEagerly) {
eagerlyValidateMethods(service);
}
returnNewProxyInstance (service.getClassLoader(), new Class<? >[] { service }, newInvocationHandler() {
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
returnserviceMethod.callAdapter.adapt(okHttpCall); }}); }Copy the code
Other implementations: use bytecode manipulation mechanisms, such as ASM, GGLB(based on ASM), Javassist, etc
Answer the question:
Here did not make answer, oneself undertake summary according to above knowledge point. In the development of APM function, dynamic proxy was used in a wide range of scenarios, and when we adapted for different models, reflection was used in many scenarios.
/** * hide system keyboard */ public voidhintSystemSoftKeyboard() {
if(getWindowToken() ! = null) { ((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getWindowToken(), 2); }if(build.version.sdk_int >= 11) {try {Class[] arrayOfClass = new Class[1]; arrayOfClass[0] = Boolean.TYPE; MethodlocalMethod = null;
if (Build.VERSION.SDK_INT < 17) {
localMethod = EditText.class.getMethod("setSoftInputShownOnFocus", arrayOfClass);
} else {
localMethod = EditText.class.getMethod("setShowSoftInputOnFocus", arrayOfClass);
}
localMethod.setAccessible(true);
Object[] arrayOfObject = new Object[1];
arrayOfObject[0] = Boolean.valueOf(false);
localMethod.invoke(this, arrayOfObject);
return;
} catch (SecurityException localSecurityException) {
localSecurityException.printStackTrace();
return;
} catch (NoSuchMethodException localNoSuchMethodException) {
localNoSuchMethodException.printStackTrace();
return;
} catch (Exception localException) {
localException.printStackTrace();
return; }}setInputType(0);
}
Copy the code
Reference:
- Proxy mode and Java implementation of dynamic proxy
- Java reflection 1 | advanced essential
- An overview of EventBus 3.0 best Practices and Principles
- Retrofit partial source code
- Geek time APP core technology about 6 | dynamic proxy is based on what principle?
- Part of the code in their own projects
Disclaimer: This is the original, please contact the author
Add an official account – programmers walking dogs, or scan the qr code below to follow relevant technical articles.