


How does java define the Union class to realize the coexistence of data bodies?
May 14, 2023 pm 03:34 PMDefine the Union class to realize the coexistence of data bodies
In C/C language, union, also known as union, is a data structure similar to structure (struct). Union (union), like structure (struct), can contain many data types and variables. The difference between the two is as follows:
All variables in the structure (struct) "coexist" ", all variables are effective at the same time, and each variable occupies a different memory space;
In a union, each variable is "mutually exclusive", and only one variable is effective at the same time. , all variables occupy the same memory space.
When multiple data need to share memory or only one of multiple data needs to be taken at a time, a union can be used.
In the Java language, there is no concept of union and structure (struct), only the concept of class. As we all know, structures can be implemented using classes. In fact, unions can also be implemented using classes. However, this class does not have the function of "multiple data need to share memory", but only the function of "only one of multiple data needs to be taken at a time".
Here, take the customer message of WeChat protocol as an example. Based on my many years of experience in interface protocol encapsulation, there are mainly two implementation methods.
1. Use function method to implement Union
Union class implementation:
/**?客戶消息類?*/@ToStringpublic?class?CustomerMessage?{????/**?屬性相關(guān)?*/ ????/**?消息類型?*/ ????private?String?msgType;????/**?目標(biāo)用戶?*/ ????private?String?toUser;????/**?共用體相關(guān)?*/ ????/**?新聞內(nèi)容?*/ ????private?News?news; ????...????/**?常量相關(guān)?*/ ????/**?新聞消息?*/ ????public?static?final?String?MSG_TYPE_NEWS?=?"news"; ????...????/**?構(gòu)造函數(shù)?*/ ????public?CustomerMessage()?{}????/**?構(gòu)造函數(shù)?*/ ????public?CustomerMessage(String?toUser)?{????????this.toUser?=?toUser; ????}????/**?構(gòu)造函數(shù)?*/ ????public?CustomerMessage(String?toUser,?News?news)?{????????this.toUser?=?toUser;????????this.msgType?=?MSG_TYPE_NEWS;????????this.news?=?news; ????}????/**?清除消息內(nèi)容?*/ ????private?void?removeMsgContent()?{????????//?檢查消息類型 ????????if?(Objects.isNull(msgType))?{????????????return; ????????}????????//?清除消息內(nèi)容 ????????if?(MSG_TYPE_NEWS.equals(msgType))?{ ????????????news?=?null; ????????}?else?if?(...)?{ ????????????... ????????} ????????msgType?=?null; ????}????/**?檢查消息類型?*/ ????private?void?checkMsgType(String?msgType)?{????????//?檢查消息類型 ????????if?(Objects.isNull(msgType))?{????????????throw?new?IllegalArgumentException("消息類型為空"); ????????}????????//?比較消息類型 ????????if?(!Objects.equals(msgType,?this.msgType))?{????????????throw?new?IllegalArgumentException("消息類型不匹配"); ????????} ????}????/**?設(shè)置消息類型函數(shù)?*/ ????public?void?setMsgType(String?msgType)?{????????//?清除消息內(nèi)容 ????????removeMsgContent();????????//?檢查消息類型 ????????if?(Objects.isNull(msgType))?{????????????throw?new?IllegalArgumentException("消息類型為空"); ????????}????????//?賦值消息內(nèi)容 ????????this.msgType?=?msgType;????????if?(MSG_TYPE_NEWS.equals(msgType))?{ ????????????news?=?new?News(); ????????}?else?if?(...)?{ ????????????... ????????}?else?{????????????throw?new?IllegalArgumentException("消息類型不支持"); ????????} ????}????/**?獲取消息類型?*/ ????public?String?getMsgType()?{????????//?檢查消息類型 ????????if?(Objects.isNull(msgType))?{????????????throw?new?IllegalArgumentException("消息類型無效"); ????????}????????//?返回消息類型 ????????return?this.msgType; ????}????/**?設(shè)置新聞?*/ ????public?void?setNews(News?news)?{????????//?清除消息內(nèi)容 ????????removeMsgContent();????????//?賦值消息內(nèi)容 ????????this.msgType?=?MSG_TYPE_NEWS;????????this.news?=?news; ????}????/**?獲取新聞?*/ ????public?News?getNews()?{????????//?檢查消息類型 ????????checkMsgType(MSG_TYPE_NEWS);????????//?返回消息內(nèi)容 ????????return?this.news; ????} ???? ????... }
Union class usage:
String?accessToken?=?...; String?toUser?=?...; List<Article>?articleList?=?...; News?news?=?new?News(articleList); CustomerMessage?customerMessage?=?new?CustomerMessage(toUser,?news); wechatApi.sendCustomerMessage(accessToken,?customerMessage);
Main advantages and disadvantages:
Advantages: Closer to the union of C/C language;
Disadvantages: The implementation logic is more complex and there are many parameter type verifications.
2. Use inheritance to implement Union
Union class implementation:
/**?客戶消息類?*/@Getter@Setter@ToStringpublic?abstract?class?CustomerMessage?{????/**?屬性相關(guān)?*/ ????/**?消息類型?*/ ????private?String?msgType;????/**?目標(biāo)用戶?*/ ????private?String?toUser;????/**?常量相關(guān)?*/ ????/**?新聞消息?*/ ????public?static?final?String?MSG_TYPE_NEWS?=?"news"; ????...????/**?構(gòu)造函數(shù)?*/ ????public?CustomerMessage(String?msgType)?{????????this.msgType?=?msgType; ????}????/**?構(gòu)造函數(shù)?*/ ????public?CustomerMessage(String?msgType,?String?toUser)?{????????this.msgType?=?msgType;????????this.toUser?=?toUser; ????} }/**?新聞客戶消息類?*/@Getter@Setter@ToString(callSuper?=?true)public?class?NewsCustomerMessage?extends?CustomerMessage?{????/**?屬性相關(guān)?*/ ????/**?新聞內(nèi)容?*/ ????private?News?news;????/**?構(gòu)造函數(shù)?*/ ????public?NewsCustomerMessage()?{????????super(MSG_TYPE_NEWS); ????}????/**?構(gòu)造函數(shù)?*/ ????public?NewsCustomerMessage(String?toUser,?News?news)?{????????super(MSG_TYPE_NEWS,?toUser);????????this.news?=?news; ????} }
Union class usage:
String?accessToken?=?...; String?toUser?=?...; List<Article>?articleList?=?...; News?news?=?new?News(articleList); CustomerMessage?customerMessage?=?new?NewsCustomerMessage(toUser,?news); wechatApi.sendCustomerMessage(accessToken,?customerMessage);
Main advantages and disadvantages :
Advantages: Use virtual base classes and subclasses for splitting, and the concepts of each subclass object are clear;
Disadvantages: Unlike C /The union of C language is very different, but the functions are generally the same.
In C/C language, the union does not include the current data type of the union. However, the Java union implemented above already contains the data type corresponding to the union. Therefore, strictly speaking, Java union is not a real union, but a class with the function of "only taking one of multiple data at a time".
The above is the detailed content of How does java define the Union class to realize the coexistence of data bodies?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c
