当前位置:网站首页>Reflective interview
Reflective interview
2022-07-18 02:00:00 【_ ady】
57. What is reflection ?
Reflection is essentially the ability to , The process of dynamically obtaining class information and dynamically executing object methods
58. What is? java serialize ? When is serialization necessary ?
serialize : take Java Object to byte stream .
Deserialization : Convert the byte stream to Java Object procedure .
situation : When Java Objects need to be transmitted over the network perhaps When persistence is stored in a file , You need to be right about Java Object for serialization processing
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/** * Test serialization , Deserialization */
public class TestSerializable implements Serializable {
private static final long serialVersionUID = 5887391604554532906L;
private int id;
private String name;
public TestSerializable(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "TestSerializable [id=" + id + ", name=" + name + "]";
}
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException, ClassNotFoundException {
// serialize
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("TestSerializable.obj"));
oos.writeObject(" Test serialization ");
oos.writeObject(618);
TestSerializable test = new TestSerializable(1, "ConstXiong");
oos.writeObject(test);
// Deserialization
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("TestSerializable.obj"));
System.out.println((String)ois.readObject());
System.out.println((Integer)ois.readObject());
System.out.println((TestSerializable)ois.readObject());
}
}
59. What is a dynamic proxy ? What are the applications ?
A dynamic proxy : When you want to give a method in a class that implements an interface , Add some extra processing .
For example, add logs , Plus business, etc . You can create a proxy for this class , Hence the name "brainstorming" is to create a new class , This class not only contains the function of the original class method , In addition, new classes with additional processing are added to the original .
This proxy class is not well defined , It's generated dynamically . It has decoupling significance , flexible , Extensibility is strong .
application :Spring Of AOP, Add log .
60. How to implement dynamic proxy ?
Realization way :2 Kind of , Respectively JDK The implementation of the ( Dynamic agent based on Interface ) and CGlib The implementation of the ( Dynamic agent based on subclass )
Dynamic agent based on Interface
Since it is an interface based dynamic proxy , Then the subclass must implement an interface . So we create interfaces and interface based subclasses
/** * Interface */
public interface IProduncer {
public void saleProduct(float money);
public void afterService(float money);
}
/** * Interface based subclasses */
public class Producer implements IProduncer{
public void saleProduct(float money){
System.out.println (" Selling products , And get the money "+money);
}
public void afterService(float money){
System.out.println (" Provide after-sales service , And get the money "+money);
}
}
/** * JDK The realization of dynamic agent */
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer ();
/** * A dynamic proxy : * characteristic : Bytecode is created on demand , Load as you go * effect : Enhance the method without modifying the source code * classification : * Dynamic agent based on Interface * Dynamic agent based on subclass * Dynamic agent based on Interface : * Class of design :Proxy * Provider :JDK official * How to create a proxy object * Use Proxy Class newProxtInstance Method * Requirements for creating proxy objects : * The proxy class implements at least one interface , If not, you can't use * newProxyInstance Method parameters : * ClassLoader: Class loader * It is used to load the bytecode of the proxy object . Use the same classloader as the proxied object . Fixed writing * Class[]: Bytecode array * It is used to make the proxy object and the proxy object have the same method . Fixed writing * InvocetionHandler: Used to provide enhanced code * It's to let us write about how agents . We usually write an implementation class of the interface , Usually it's an anonymous inner class , But it's not necessary * The implementation classes of this interface are written by who */
IProduncer proxyProducer = (IProduncer) Proxy.newProxyInstance (producer.getClass ( ).getClassLoader ( ),
producer.getClass ( ).getInterfaces ( ),
new InvocationHandler () {
/** * Any interface method that executes the proxied object passes through this method * Meaning of method parameters : * @param proxy References to proxy objects * @param method The current method of execution * @param args Parameters required for the current execution method * @return It has the same return value as the represented object method * @throws Throwable */
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Provide enhanced purchasing
Object returnVlaue = null;
//1 Get the parameters of method execution
Float money = (Float) args[0];
//2 Determine if the current method is a sale
if("saleProduct".equals (method.getName ())){
// The proxy method is enhanced .
returnVlaue = method.invoke (producer, money*0.8f);
}
return returnVlaue;
}
});
proxyProducer.saleProduct (10000f);
}
}
Dynamic agent based on subclass
/** * Subclass */
public class Producer {
public void saleProduct(float money){
System.out.println (" Selling products , And get the money "+money);
}
public void afterService(float money){
System.out.println (" Provide after-sales service , And get the money "+money);
}
}
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer ();
/** * A dynamic proxy : * characteristic : Bytecode is created on demand , Load as you go * effect : Enhance the method without modifying the source code * classification : * Dynamic agent based on Interface * Dynamic agent based on subclass * Dynamic agent based on subclass : * Class of design :Emhancer * Provider : The third party cglib library * How to create a proxy object * Use Enhancer Medium create Method * Requirements for creating proxy objects : * The proxied class cannot be the final class * create Method parameters : * Class: Bytecode * It is the bytecode used to specify the proxy object * callback: Used to provide enhanced * We usually write the sub interface implementation class of this interface :MethodInterceptor * * */
Producer cglibProducer = (Producer) Enhancer.create (producer.getClass (), new MethodInterceptor ( ) {
/** * * @param proxy * @param method * @param args * @param methodProxy: The proxy object of the current execution method * @return * @throws Throwable */
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
// Provide enhanced purchasing
Object returnVlaue = null;
//1 Get the parameters of method execution
Float money = (Float) args[0];
//2 Determine if the current method is a sale
if("saleProduct".equals (method.getName ())){
returnVlaue = method.invoke (producer, money*0.8f);
}
return returnVlaue;
}
});
cglibProducer.saleProduct (10000);
}
}
| Compare | Subclass | Interface |
|---|---|---|
| Class of design | Enhancer | Proxy |
| Provider | Cglib | JDK |
| Proxy object creation | Enhance.creat Method | Proxy Of newProxyInstance Method |
| Parameters required for proxy object creation | Bytecode of proxy object subclass ,callback Enhanced class of interface (MethodInterceptor()) | Class loader for proxy object , Proxy object interface ,InvocetionHandler Enhancement class |
| invoke Parameters | Proxy object subclasses , Method parameters |
边栏推荐
- VDD,VCC,VSS,GND,地之间有何区别?
- Matlab summary
- Servlet api code example: server version confession wall
- matlab 画图例题篇
- Redis profile
- 快速傅里叶变换
- For collecting lost rights and interests, is it still worth digging into the content of enterprise stations?
- Compare the high-quality [test report] template with your own?
- 10分钟自定义搭建行人分析系统,检测跟踪、行为识别、人体属性All-in-One!
- Engineering monitoring vibrating wire sensor wireless acquisition instrument external digital sensor
猜你喜欢

51 single chip microcomputer serial port baud rate (keep it and don't look everywhere)

Introduction to redis

What are the problems we need to pay attention to in setting the standard of Baidu search basic information?

软件测试-基础篇

Enterprise station, there is ranking, no traffic, how to do?

【C】 Creation and destruction of function stack frames
![[HCIA] OSI model](/img/e2/bfbd7f9b452d4f755be43f5c91f37e.png)
[HCIA] OSI model

51单片机串口波特率(保留一下以后就不用到处找了)

How to do Zhihu SEO and how to improve Zhihu SEO ranking?

Idea setting / modifying shortcut keys
随机推荐
What are the problems we need to pay attention to in setting the standard of Baidu search basic information?
Pat brush questions
送你的代码上太空,与华为云一起开发“最伟大的作品”
Nodes and clients for getting started with eth
【C】 Creation and destruction of function stack frames
Redis persistence - RDB
30万奖池等你来战!自然语言处理(NLP)赛事合集来啦
第四十期:JS函数默认参数引发的思考
Introduction to redis
fast Fourier transform
redis持久化——rdb
Matlab drawing examples
High weight website has not been filed. Is it normal to reduce the weight in batches?
[C exercise] input the month and year, and calculate the number of days in the month
Issue 35: preparation before flutter development
The domain name has been filed, and the trading is strictly controlled. Do you know?
LeetCode 剑指 Offer 53 - I. 在排序数组中查找数字 I 03
C# Winform窗体基础属性
apt-get 无法使用 语法报错
.net core 配置跨域