├── .circleci └── config.yml ├── .coveralls.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── src ├── main └── java │ └── org │ └── enumus │ ├── EnumMapValidator.java │ ├── Hierarchy.java │ ├── Mirror.java │ ├── ValueOf.java │ ├── ValueOfRange.java │ ├── functions │ └── UnsafeBiFunction.java │ └── initializer │ ├── Argument.java │ ├── BooleanValue.java │ ├── BooleanValues.java │ ├── ByteValue.java │ ├── ByteValues.java │ ├── CharValue.java │ ├── CharValues.java │ ├── DateValue.java │ ├── DateValues.java │ ├── DoubleValue.java │ ├── Initializable.java │ ├── IntValue.java │ ├── IntValues.java │ ├── LongValue.java │ ├── LongValues.java │ ├── PatternValue.java │ ├── ShortValue.java │ ├── ShortValues.java │ ├── Util.java │ ├── Value.java │ ├── ValueData.java │ └── Values.java └── test └── java └── org └── enumus ├── EnumMapValidatorTest.java ├── HierarchyTest.java ├── InitializationTest.java ├── MirrorTest.java ├── ValueOfTest.java ├── initializer └── UtilTest.java └── samples ├── Color.java ├── Color2.java ├── Environment.java ├── ManualColor.java ├── MathConstant.java ├── OsType.java ├── Platform.java ├── RainbowColors1.java ├── Rgb.java ├── RuntimeEnvironment.java ├── Shade.java ├── Software.java └── article ├── IsoAlpha2.java ├── enumwitannotations ├── Country.java └── IsoCountryCode.java ├── withenum └── Country.java └── withoutenum └── Country.java /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | 5 | working_directory: ~/circleci-enumus 6 | 7 | docker: 8 | - image: circleci/openjdk:8-stretch-node-browsers-legacy 9 | 10 | steps: 11 | 12 | - checkout 13 | 14 | - run: ./gradlew build 15 | 16 | - store_test_results: 17 | path: build/test-results/test 18 | 19 | - store_artifacts: 20 | path: build/libs/enumus-1.0-SNAPSHOT.jar 21 | 22 | -------------------------------------------------------------------------------- /.coveralls.yml: -------------------------------------------------------------------------------- 1 | service_name: travis-pro 2 | repo_token: x9EjguH3aDhwRIsV9aiARg 3 | 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | 21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 22 | hs_err_pid* 23 | 24 | *.iml 25 | .idea 26 | 27 | */build/* 28 | */target/* 29 | */classes/* 30 | .gradle/* 31 | 32 | build/* 33 | target/* 34 | classes/* 35 | out/* 36 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk9 4 | before_script: 5 | - chmod +x gradlew 6 | script: 7 | - ./gradlew clean build 8 | - ./gradlew jacocoTestReport 9 | after_success: 10 | - bash <(curl -s https://codecov.io/bash) 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # enumus 2 | 3 | [![CircleCI](https://circleci.com/gh/alexradzin/enumus/tree/master.svg?style=svg)](https://circleci.com/gh/alexradzin/enumus/tree/master) 4 | [![Build Status](https://travis-ci.com/alexradzin/enumus.svg?branch=master)](https://travis-ci.com/alexradzin/enumus) 5 | [![codecov](https://codecov.io/gh/alexradzin/enumus/branch/master/graph/badge.svg)](https://codecov.io/gh/alexradzin/enumus) 6 | [![Codacy Badge](https://api.codacy.com/project/badge/Grade/ea86efcce7224cc294cd8d550fe63a82)](https://www.codacy.com/app/alexradzin/enumus?utm_source=github.com&utm_medium=referral&utm_content=alexradzin/enumus&utm_campaign=Badge_Grade) 7 | 8 | A set of utilities that make java enums more powerful. 9 | 10 | ## Features 11 | * [Customized `valueOf()` (implementation of `valueOf()` based on any `enum` field and not on name as standard implementation)](README.md#Customized-`valueOf()`) 12 | * [`valueOf()` based on value range](README.md#Range-based-`valueOf()`) 13 | * [Enum map validator](README.md#Enum-map-validator) 14 | * [Mirror `enum`](README.md#Mirror-`enum`) 15 | * [Hierarchical `enum`](README.md#Hierarchical-`enum`) 16 | * [Initialization using annotations](README.md#Initialization-using-annotations) 17 | 18 | ## Customized `valueOf()` 19 | Enum have a very convinient built-in feature - static function `valueOf()` that retrieves enum constant by its name. 20 | In some cases however we need something similar but based on other field. The implementation is simple: create static map, 21 | iterate over values of enum and populate the map. 22 | 23 | ```java 24 | public enum Color { 25 | RED("red"), GREEN("green"), BLUE("blue"),; 26 | private final String title; 27 | ManualColor(String title) { 28 | this.title = title; 29 | } 30 | } 31 | ``` 32 | 33 | Thanks to Java 8 we can now right this using one line only: 34 | 35 | ```java 36 | private static final Map titles = Arrays.stream(Color.values()).collect(Collectors.toMap(Color::getTitle, e -> e)); 37 | ``` 38 | I found myself writing similar code many times and decidded to implemnent utility that simplifies this. Now the code can look like the following: 39 | 40 | ```java 41 | private static final ValueOf titles = new ValueOf<>(Color.class, e -> e.title); 42 | ``` 43 | 44 | The static accessor is simple too. It should not care about throwing exception if value is not found. 45 | 46 | ```java 47 | public static Color valueOfTitle(String title) { 48 | return titles.valueOf(title); 49 | } 50 | ``` 51 | 52 | The utity accepts reference to function that can implement more complicated logic than just accessing a simple field. 53 | 54 | ### Range based `valueOf()` 55 | The utility supports ranges as well. Visible colors are just electro magnetic waves of certain length. 56 | 57 | | Color | Wave length, nm | 58 | |--------|-----------------| 59 | | Red | 700–635 | 60 | | Orange | 635–590 | 61 | | Yellow | 590–560 | 62 | | Green | 560–520 | 63 | 64 | We want to define enum `Rgb` and get enum constant by wave length from the range. It is very easy with enumus: 65 | 66 | ```java 67 | public enum Rgb { 68 | RED(635, 700), GREEN(520, 560), BLUE(450, 490),; 69 | private static final ValueOfRange waveLength = new ValueOfRange<>(Rgb.class, e -> e.min, e -> e.max); 70 | private final int min; 71 | private final int max; 72 | Rgb(int min, int max) { 73 | this.min = min; 74 | this.max = max; 75 | } 76 | public static Rgb valueByWaveLength(int wave) { 77 | return waveLength.valueOf(wave); 78 | } 79 | ``` 80 | 81 | ## Enum map validator 82 | It is very useful practice to use `enum` constants as the map keys. Values may contain either simple data, complex objects or often functions. Very often we want to have entry per each `enum` element. Unfortunately compiler will not help us to detect if new element was added to enum. In this case code can fail at rutime. Enumus helps to solve this problem: 83 | 84 | ```java 85 | EnumMapValidator.validateKeys(Color.class, map, "Colors map"); 86 | ``` 87 | 88 | If for instance `map` does not contain entry `BLUE` the line above will throw `IllegalStateException` with message `"Colors map is not complete: [RED, GREEN, [BLUE]] (keys in squire brackets are absent)"` 89 | 90 | ## Mirror `enum` 91 | Enums can hold data and implement methods. However not all methods can be implemented in one class. Methods may delegate functionality to other classes that require external dependencies. Often we do not want to put all dependencies into one module but rather separate them among several modules. Sometimes this cause us to hold 2 or more `enum`s with the same constants and different implementation. This can be used instead of classic [Visitor pattern](https://en.wikipedia.org/wiki/Visitor_pattern) but even has advantage: some implementations may be optional and we can check whether the implementation is done or not without calling the actual function. 92 | 93 | Enumus introduces term "morror" `enum`, that is `enum` that has the same entries as its mirror. The feature may be comapred with 2 classes that implement the same interface. In this case compiler checks that all methods are implemented. Mirror enum cannot enjoy the compiler's service but it is enough add one line of code in static initialiazer and exception will be thrown if enum does not reflect its mirror. 94 | 95 | ```java 96 | enum MissingColor { 97 | RED, GREEN,; 98 | static { 99 | Mirror.mirrors(MissingColor.class, Color.class); // throws exception because BLUE is absent 100 | } 101 | } 102 | ``` 103 | 104 | ## Hierarchical `enum` 105 | 106 | Neither `enum`s nor their elements cannot be inherited from other class. It is becase each `enum` is inherited implicitly from `java.lang.Enum`. Some tasks however can be easier modelled using hierarchy. Enumus helps to implement hieratchical structure with `enum`s. 107 | 108 | ```java 109 | public enum OsType { 110 | OS(null), 111 | Windows(OS), 112 | WindowsNT(Windows), 113 | WindowsNTWorkstation(WindowsNT), 114 | WindowsNTServer(WindowsNT), 115 | Windows2000(Windows), 116 | Windows2000Server(Windows2000), 117 | Windows2000Workstation(Windows2000), 118 | WindowsXp(Windows), 119 | WindowsVista(Windows), 120 | Windows7(Windows), 121 | Windows95(Windows), 122 | Windows98(Windows), 123 | Unix(OS) { 124 | @Override 125 | public boolean supportsXWindowSystem() { 126 | return true; 127 | } 128 | }, 129 | Linux(Unix), 130 | IOS(Linux), 131 | Android(Linux), 132 | AIX(Unix), 133 | HpUx(Unix), 134 | SunOs(Unix),; 135 | private OsType parent; 136 | OsType(OsType parent) { 137 | this.parent = parent; 138 | } 139 | } 140 | ``` 141 | 142 | The structure above is defined using standard Java syntax; there is no need to use external tools. However the following features may be needed here: 143 | * we cannot easily get list of all children of `Linux` 144 | * How to check that `WindowsVista` is `Windows`? 145 | * How to "inherit" method `supportsXWindowSystem()` in all Unix like systems? 146 | 147 | All these can be easily done with class `Hierarchy` implemented by enumus. Just add the following line: 148 | 149 | ```java 150 | private static Hierarchy hierarchy = new Hierarchy<>(OsType.class, e -> e.parent); 151 | ``` 152 | and implementation of described above methods becomes trivial: 153 | 154 | ```java 155 | public OsType[] children() { 156 | return hierarchy.getChildren(this); 157 | } 158 | public boolean supportsXWindowSystem() { 159 | return hierarchy.invoke(this, args -> false); 160 | } 161 | public boolean isA(OsType other) { 162 | return hierarchy.relate(other, this); 163 | } 164 | ``` 165 | 166 | ## Initialization using annotations 167 | Almost each appllication contains series of constant values like these: 168 | 169 | ```java 170 | public static final String THREAD_COUNT_PROPERTY = "THREAD_COUNT_PROPERTY"; 171 | public static final int THREAD_COUNT_DEFAULT = 10; 172 | public static final String CONNECTION_TIMEOUT_PROPERTY = "CONNECTION_TIMEOUT_PROPERTY"; 173 | public static final int CONNECTION_TIMEOUT_DEFAULT = 10_000; 174 | ``` 175 | 176 | It is convenient to organize such constants using enums. For example instead of having a lot of groups of `static final` members we can put them into enum like following: 177 | 178 | ```java 179 | enum Configuration { 180 | THREAD_COUNT(10), NETWORK_TIMEOUT(10_000),; 181 | private final int value; 182 | Configuration(int value) {this.value = value} 183 | public int value() {return value;} 184 | public String property() {return name() + "_PROPERTY";} 185 | } 186 | ``` 187 | 188 | Such enums tend to grow quickly. Sometimes they contain values that match wourse than those in example above. For exampele connection may hold read/write timeouts while threading model may become more flexible and contain minimum, maximum and default thread count. In this case we have either break the enum into separate parts or add all fields needed for all different elements together: 189 | 190 | ```java 191 | enum Configuration { 192 | THREAD_COUNT(5, 20, 10, 0, 0), // read/write timeout is irrelevant here, so we pass 0 instead 193 | NETWORK_TIMEOUT(0, 0, 10_000, 5_000, 8_000),; // min/max values are irrelevant for timeout 194 | private final int min; 195 | private final int max; 196 | private final int value; 197 | 198 | private final int read; 199 | private final int write; 200 | 201 | Configuration(int min, int max, int value, int read, int write) {/* initialization code*/} 202 | } 203 | ``` 204 | 205 | The definitions of the enum elements became ugly. We have to pass irrelevant values just to satisfy compiler. 206 | We can define several overloaded constructors that better suite our cases. But it is not always possible. For example in this example we would liek to have 2 additional constructors: 207 | 208 | ```java 209 | Configuration(int min, int max, int value) {/* initialization code*/} 210 | Configuration(int value, int read, int write) {/* initialization code*/} 211 | ``` 212 | 213 | But we cannot do this because both constructors have the same signature: 3 `int` parameters. 214 | In real life number of parameter variations may be much higher. 215 | Enumus suggests solution for this. 216 | 217 | Enums are inititated when they are accessed first time, typically on JVM startup. So, performance is not an issue here. This means that the configuration could be done using annotations without impact on application performance. Enumus provides an extendable type safe annotation based framework for configuration of `enum` elements: 218 | 219 | Integer value configured using annotation 220 | ```java 221 | @IntValue(name = "number", value = 2) 222 | TWO(), 223 | ``` 224 | 225 | String value configured using annotation 226 | ```java 227 | @Value(name = "str", value = "two") 228 | TWO(),; 229 | ``` 230 | 231 | Here is full example that can illustrate the usage: 232 | 233 | ```java 234 | public enum OneDoubleParamTestEnum implements Initializable { 235 | ZERO(), // using default constructor; the double value will be initialized to 0.0 236 | PI(3.1415926), // using regular constructor 237 | @DoubleValue(name = "number", value = 2.718281828) 238 | E(); // the value is initialiezed using annotation 239 | 240 | private final double number; 241 | 242 | OneDoubleParamTestEnum() { 243 | number = $(); // default constructor that calls $() function implemented in interface Initializable 244 | } 245 | OneDoubleParamTestEnum(double number) { 246 | this.number = number; // regular constructor 247 | } 248 | } 249 | ``` 250 | 251 | Almost any type of argument can be supported. The following types are supported out of the box: 252 | * `String` 253 | * `int` 254 | * `double` 255 | * `java.util.Date` 256 | * `java.util.regex.Pattern` 257 | * any `enum` type 258 | 259 | 260 | 261 | 262 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | ext.junitJupiterVersion = '5.0.0-M4' 2 | 3 | 4 | apply plugin: 'java' 5 | //apply plugin: 'org.junit.platform.gradle.plugin' 6 | apply plugin: 'jacoco' 7 | 8 | sourceCompatibility = 1.8 9 | version = '1.0-SNAPSHOT' 10 | 11 | compileTestJava { 12 | sourceCompatibility = 1.8 13 | targetCompatibility = 1.8 14 | options.compilerArgs += '-parameters' 15 | } 16 | 17 | repositories { 18 | if (project.hasProperty("local_repository") || System.getProperty("local_repository") != null) { 19 | mavenLocal() 20 | } else { 21 | mavenCentral() 22 | } 23 | } 24 | 25 | dependencies { 26 | testCompileOnly( 27 | 'junit:junit:4.12' 28 | ) 29 | testImplementation( 30 | 'org.junit.jupiter:junit-jupiter-api:5.1.0' 31 | ) 32 | testRuntimeOnly( 33 | 'org.junit.jupiter:junit-jupiter-engine:5.1.0', 34 | 'org.junit.vintage:junit-vintage-engine:5.1.0' 35 | ) 36 | } 37 | 38 | test { 39 | testLogging { 40 | events 'PASSED', 'FAILED', 'SKIPPED' 41 | } 42 | useJUnitPlatform() 43 | } 44 | 45 | 46 | 47 | jacoco { 48 | toolVersion = "0.8.10" 49 | } 50 | 51 | 52 | jacocoTestReport { 53 | reports { 54 | xml.required = true 55 | html.required = false 56 | } 57 | } 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alexradzin/enumus/d2597b9980c7bace30c12eec469e472c292ba5a2/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/EnumMapValidator.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import java.util.Arrays; 4 | import java.util.Map; 5 | import java.util.Set; 6 | import java.util.function.Function; 7 | import java.util.function.Predicate; 8 | import java.util.function.Supplier; 9 | import java.util.stream.Collectors; 10 | 11 | import static java.lang.String.format; 12 | 13 | public class EnumMapValidator { 14 | public static , V> void validateKeys(Class clazz, Map map, String mapName) { 15 | validate(clazz, mapName, "keys", map::size, map::containsKey, Enum::name); 16 | } 17 | 18 | public static > void validateValues(Class clazz, Map map, String mapName) { 19 | validate(clazz, mapName, "values", map::size, map::containsValue, Enum::name); 20 | } 21 | 22 | public static > void validateElements(Class clazz, Set set, String mapName) { 23 | validate(clazz, mapName, "elements", set::size, set::contains, Enum::name); 24 | } 25 | 26 | 27 | 28 | public static > void validate(Class clazz, String containerTitle, String elementTitle, Supplier size, Predicate contains, Function name) { 29 | T[] elements = clazz.getEnumConstants(); 30 | if (elements.length != size.get()) { 31 | throw new IllegalStateException(format("%s is not complete: %s (%s in squire brackets are absent)", 32 | containerTitle, 33 | Arrays.stream(elements).map(e -> contains.test(e) ? name.apply(e) : "[" + name.apply(e) + "]").collect(Collectors.toList()), 34 | elementTitle)); 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/Hierarchy.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import java.lang.reflect.Array; 4 | import java.lang.reflect.Method; 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.Collection; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Optional; 11 | import java.util.function.Function; 12 | 13 | public class Hierarchy> { 14 | private final Function parentAccessor; 15 | private final Map children = new HashMap<>(); 16 | 17 | 18 | public Hierarchy(Class type, Function parentAccessor) { 19 | this.parentAccessor = parentAccessor; 20 | 21 | Map> hm = new HashMap<>(); 22 | Arrays.stream(type.getEnumConstants()).forEach(e -> { 23 | T parent = parentAccessor.apply(e); 24 | Collection l = hm.getOrDefault(parentAccessor.apply(e), new ArrayList<>()); 25 | l.add(e); 26 | hm.put(parent, l); 27 | hm.putIfAbsent(e, new ArrayList<>()); 28 | }); 29 | 30 | populateChildren(type, hm); 31 | } 32 | 33 | @SuppressWarnings("unchecked") 34 | private void populateChildren(Class type, Map> hm) { 35 | hm.forEach((key, value) -> children.put(key, value.toArray((T[]) Array.newInstance(type, value.size())))); 36 | } 37 | 38 | @SuppressWarnings("WeakerAccess") // can be called from outside this class if needed. 39 | public T getParent(T element) { 40 | return parentAccessor.apply(element); 41 | } 42 | 43 | 44 | public T[] getChildren(T element) { 45 | return children.get(element); 46 | } 47 | 48 | // ascendant -- parent 49 | // descendant -- child 50 | public boolean relate(T ascendant, T descendant) { 51 | for (T elem = descendant; elem != null; elem = parentAccessor.apply(elem)) { 52 | if (elem == ascendant) { 53 | return true; 54 | } 55 | } 56 | return false; 57 | } 58 | 59 | public R invoke(T element, Function defaultImpl, Object ... args) { 60 | String methodName = new Throwable().getStackTrace()[1].getMethodName(); 61 | for (T elem = element; elem != null; elem = getParent(elem)) { 62 | Optional result = invokeMethod(elem, methodName, args); 63 | if (result.isPresent()) { 64 | return result.get(); 65 | } 66 | } 67 | 68 | return defaultImpl.apply(args); 69 | } 70 | 71 | 72 | private Optional invokeMethod(T object, String methodName, Object ... args) { 73 | @SuppressWarnings("unchecked") 74 | Class clazz = (Class)object.getClass(); 75 | Class enumClass = object.getDeclaringClass(); 76 | 77 | 78 | if (enumClass.equals(clazz)) { 79 | return Optional.empty(); 80 | } 81 | 82 | Optional method = Arrays.stream(clazz.getMethods()).filter(m -> m.getName().equals(methodName)).findFirst(); 83 | if (method.isPresent()) { 84 | if (method.get().getDeclaringClass().equals(enumClass)) { 85 | return Optional.empty(); 86 | } 87 | try { 88 | Method m = method.get(); 89 | m.setAccessible(true); 90 | @SuppressWarnings("unchecked") 91 | R result = (R)m.invoke(object, args); 92 | return Optional.ofNullable(result); 93 | } catch (ReflectiveOperationException e) { 94 | throw new IllegalStateException(e); 95 | } 96 | } 97 | return Optional.empty(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/Mirror.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import static java.lang.String.format; 4 | import static java.util.Arrays.stream; 5 | 6 | public class Mirror { 7 | @SuppressWarnings("unchecked") 8 | @SafeVarargs 9 | public static > void of(Class image, Class ... images) throws IllegalStateException { 10 | Class caller = discoverCaller(); 11 | if (!Enum.class.isAssignableFrom(caller)) { 12 | throw new IllegalStateException(format("Caller of Mirror.of() %s is not enum", caller.getName())); 13 | } 14 | Mirror.mirrors(caller, image, images); 15 | } 16 | 17 | @SuppressWarnings("unchecked") 18 | private static > Class discoverCaller() { 19 | try { 20 | return (Class)Class.forName(stream(new Throwable().getStackTrace()).filter(e -> !e.getClassName() 21 | .equals(Mirror.class.getName())) 22 | .findFirst() 23 | .orElseThrow(() -> new IllegalStateException(format("Cannot discover caller's class. It seems that %s calls itself", Mirror.class.getName()))) 24 | .getClassName()); 25 | } catch (ClassNotFoundException e) { 26 | throw new IllegalStateException(e); 27 | } 28 | } 29 | 30 | 31 | @SuppressWarnings({"SuspiciousSystemArraycopy", "WeakerAccess"}) 32 | @SafeVarargs 33 | public static , M extends Enum> void mirrors(Class mirror, Class image, Class ... images) { 34 | T[] mirrorConstants = mirror.getEnumConstants(); 35 | @SuppressWarnings("unchecked") // the luck of generic arrays. 36 | Class[] allImages = new Class[images.length + 1]; 37 | allImages[0] = image; 38 | System.arraycopy(images, 0, allImages, 1, images.length); 39 | 40 | int i = 0; 41 | for (Class img : allImages) { 42 | if (mirror.equals(img)) { 43 | throw new IllegalArgumentException(format("Class %s cannot be mirror of itself", mirror.getName())); 44 | } 45 | M[] imgEnumConstants = img.getEnumConstants(); 46 | for (int j = 0; i < mirrorConstants.length && j < imgEnumConstants.length; j++, i++) { 47 | if (!mirrorConstants[i].name().equals(imgEnumConstants[j].name())) { 48 | throw new IllegalStateException(format("Element #%d of mirror %s.%s does not reflect the source %s.%s", j, image.getName(), imgEnumConstants[j], mirror.getName(), mirrorConstants[i])); 49 | } 50 | } 51 | } 52 | if (i != mirrorConstants.length) { 53 | throw new IllegalStateException(format("Source and mirror enums have different number of elements: %s#%d vs. %s#%d", mirror.getName(), mirrorConstants.length, image.getName(), i)); 54 | } 55 | 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/ValueOf.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.Map; 6 | import java.util.TreeMap; 7 | import java.util.function.Function; 8 | import java.util.stream.Collectors; 9 | 10 | import static java.lang.String.format; 11 | import static java.util.Optional.ofNullable; 12 | 13 | public class ValueOf, F> { 14 | private static final String ERROR_MESSAGE = "No enum constant %s.%s"; 15 | private final Class type; 16 | private final Map values; 17 | 18 | public ValueOf(Class type, Function fieldAccessor) { 19 | this.type = type; 20 | this.values = Arrays.stream(type.getEnumConstants()).collect(Collectors.toMap(fieldAccessor, e -> e)); 21 | } 22 | 23 | public ValueOf(Class type, Function fieldAccessor, Comparator c) { 24 | this.type = type; 25 | this.values = Arrays.stream(type.getEnumConstants()).collect(Collectors.toMap(fieldAccessor, e -> e, (a,b) -> a, () -> new TreeMap<>(c))); 26 | } 27 | 28 | public T valueOf(F key) { 29 | return ofNullable(values.get(key)).orElseThrow(() -> new IllegalArgumentException(format(ERROR_MESSAGE, type.getName(), key))); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/ValueOfRange.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import java.util.Arrays; 4 | import java.util.Map; 5 | import java.util.NavigableMap; 6 | import java.util.Objects; 7 | import java.util.TreeMap; 8 | import java.util.function.Function; 9 | 10 | import static java.lang.String.format; 11 | 12 | public class ValueOfRange, F extends Comparable> { 13 | private static final String ERROR_MESSAGE = "No enum constant %s.%s"; 14 | private final Class type; 15 | private final NavigableMap values; 16 | public ValueOfRange(Class type, Function floorAccessor, Function ceilingAccessor) { 17 | this.type = type; 18 | values = new TreeMap<>(); 19 | fill(values, type.getEnumConstants(), floorAccessor); 20 | fill(values, type.getEnumConstants(), ceilingAccessor); 21 | } 22 | 23 | private static void fill(Map map, T[] values, Function keyCreator) { 24 | Arrays.stream(values).forEach(t -> map.put(keyCreator.apply(t), t)); 25 | } 26 | 27 | public T valueOf(F key) { 28 | Map.Entry f = values.floorEntry(key); 29 | Map.Entry c = values.ceilingEntry(key); 30 | if (f != null && c != null && Objects.equals(f.getValue(), c.getValue())) { 31 | return f.getValue(); 32 | } 33 | throw new IllegalArgumentException(format(ERROR_MESSAGE, type.getName(), key)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/functions/UnsafeBiFunction.java: -------------------------------------------------------------------------------- 1 | package org.enumus.functions; 2 | 3 | public interface UnsafeBiFunction { 4 | R apply(T t, U u) throws E; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/Argument.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Documented 10 | @Retention(RetentionPolicy.RUNTIME) 11 | @Target(ElementType.ANNOTATION_TYPE) 12 | public @interface Argument { 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/BooleanValue.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Repeatable; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Argument 10 | @Repeatable(BooleanValues.class) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.FIELD) 13 | public @interface BooleanValue { 14 | String name(); 15 | boolean[] value(); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/BooleanValues.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Argument 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | public @interface BooleanValues { 12 | BooleanValue[] value(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/ByteValue.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Repeatable; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Argument 10 | @Repeatable(ByteValues.class) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.FIELD) 13 | public @interface ByteValue { 14 | String name(); 15 | byte[] value(); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/ByteValues.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Argument 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | public @interface ByteValues { 12 | ByteValue[] value(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/CharValue.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Repeatable; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Argument 10 | @Repeatable(CharValues.class) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.FIELD) 13 | public @interface CharValue { 14 | String name(); 15 | char[] value(); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/CharValues.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Argument 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | public @interface CharValues { 12 | CharValue[] value(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/DateValue.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | import java.text.SimpleDateFormat; 8 | import java.util.Date; 9 | 10 | @Argument 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.FIELD) 13 | @Value(name = "${name}", value = "${value}", type = Date.class, factory = SimpleDateFormat.class, factoryMethod = "parse") 14 | @Value(name = "factoryArgument", value = "${format}") 15 | public @interface DateValue { 16 | String name(); 17 | String value(); 18 | String format() default "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // example: 2001-07-04T12:08:56.235-0700 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/DateValues.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Argument 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | public @interface DateValues { 12 | DateValue[] value(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/DoubleValue.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Argument 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | public @interface DoubleValue { 12 | String name(); 13 | double[] value(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/Initializable.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Field; 5 | import java.lang.reflect.Modifier; 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.HashMap; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.concurrent.atomic.AtomicInteger; 12 | import java.util.stream.Collectors; 13 | 14 | public interface Initializable { 15 | Map defaultValues = new HashMap() {{ 16 | put(int.class, 0); 17 | put(long.class, 0); 18 | put(short.class, 0); 19 | put(byte.class, (byte)0); 20 | put(float.class, 0.0F); 21 | put(double.class, 0.0); 22 | put(boolean.class, false); 23 | put(char.class, (char)0); 24 | }}; 25 | 26 | 27 | Map initializationContext = new HashMap<>(); 28 | 29 | class ClassData { 30 | StringBuilder currentMember = new StringBuilder(); 31 | AtomicInteger fieldCount = new AtomicInteger(0); 32 | List fields = new ArrayList<>(); 33 | } 34 | 35 | default T argument() { 36 | return argument(null); 37 | } 38 | 39 | 40 | default T argument(T defaultValue) { 41 | return $(defaultValue); 42 | } 43 | 44 | default T $() { 45 | return $(null); 46 | } 47 | 48 | 49 | default T $(T defaultValue) { 50 | Class clazz = getClass(); 51 | if (!clazz.isEnum()) { 52 | clazz = clazz.getSuperclass(); 53 | if (!clazz.isEnum()) { 54 | throw new IllegalStateException(String.format("Class %s is not an enum", clazz.getName())); 55 | } 56 | } 57 | String name = Util.name(this); 58 | ClassData context = initializationContext.getOrDefault(clazz, new ClassData()); 59 | initializationContext.putIfAbsent(clazz, context); 60 | 61 | 62 | if (context.fields.isEmpty()) { 63 | context.fields.addAll(Util.dataFields(this)); 64 | } 65 | 66 | 67 | if (!context.currentMember.toString().equals(name)) { 68 | context.currentMember.setLength(0); 69 | context.currentMember.append(name); 70 | context.fieldCount.set(0); 71 | } 72 | Annotation[] annotations = Util.annotations(this, name); 73 | Field param = Arrays.stream(clazz.getDeclaredFields()).filter(f -> !Modifier.isStatic(f.getModifiers())).collect(Collectors.toList()).get(context.fieldCount.get()); //[fieldCount.get()]; 74 | String paramName = param.getName(); 75 | @SuppressWarnings("unchecked") 76 | T value = (T)Arrays.stream(annotations) 77 | .map(a -> Util.isContainer(a) ? Util.invoke(a, Util.method(a.annotationType(), "value")) : new Annotation[] {a}) 78 | .flatMap(Arrays::stream) 79 | .filter(a -> a.annotationType().getAnnotation(Argument.class) != null) 80 | .filter(a -> Util.name(a).equals(paramName)) 81 | .findFirst() 82 | .map(a -> Util.create(a, param.getType())) 83 | .orElseGet(() -> defaultValue == null ? defaultValues.get(param.getType()) : defaultValue); 84 | 85 | context.fieldCount.incrementAndGet(); 86 | return value; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/IntValue.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Repeatable; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Argument 10 | @Repeatable(IntValues.class) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.FIELD) 13 | public @interface IntValue { 14 | String name(); 15 | int[] value(); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/IntValues.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Argument 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | public @interface IntValues { 12 | IntValue[] value(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/LongValue.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Repeatable; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Argument 10 | @Repeatable(LongValues.class) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.FIELD) 13 | public @interface LongValue { 14 | String name(); 15 | long[] value(); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/LongValues.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Argument 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | public @interface LongValues { 12 | LongValue[] value(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/PatternValue.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | import java.util.regex.Pattern; 8 | 9 | @Argument 10 | @Value(name = "${name}", value = {"${regex}", "${options}"}, type = Pattern.class, factory = Pattern.class, factoryMethod = "compile") 11 | @Value(name = "factoryMethodArgument", value = "${regex}") 12 | @Value(name = "factoryMethodArgument", value = "${options}") 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Target(ElementType.FIELD) 15 | public @interface PatternValue { 16 | String name(); 17 | String regex(); 18 | int options() default 0; 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/ShortValue.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Repeatable; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Argument 10 | @Repeatable(ShortValues.class) 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target(ElementType.FIELD) 13 | public @interface ShortValue { 14 | String name(); 15 | short[] value(); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/ShortValues.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Argument 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | public @interface ShortValues { 12 | ShortValue[] value(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/Util.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Field; 5 | import java.lang.reflect.Method; 6 | import java.lang.reflect.Modifier; 7 | import java.util.Arrays; 8 | import java.util.List; 9 | import java.util.stream.Collectors; 10 | 11 | import static java.lang.String.format; 12 | 13 | class Util { 14 | static String name(Object self) { 15 | try { 16 | return (String) self.getClass().getMethod("name").invoke(self); 17 | } catch (ReflectiveOperationException e) { 18 | throw new IllegalStateException(e); 19 | } 20 | } 21 | 22 | static List dataFields(Object self) { 23 | return Arrays.stream(self.getClass().getDeclaredFields()) 24 | .filter(f -> !Modifier.isStatic(f.getModifiers())) 25 | .collect(Collectors.toList()); 26 | 27 | } 28 | 29 | static Annotation[] annotations(Object self, String name) { 30 | try { 31 | return Arrays.stream(self.getClass().getField(name).getAnnotations()) 32 | .filter(a -> a.annotationType().getAnnotation(Argument.class) != null).toArray(Annotation[]::new); 33 | } catch (NoSuchFieldException e) { 34 | throw new IllegalArgumentException(format("Field %s does not exist in enum %s", name, self.getClass())); 35 | } 36 | } 37 | 38 | static T create(Annotation a, Class type) { 39 | return createValueData(a).createInstance(type); 40 | //return new FactoryCreator().apply(d).apply(d.factoryMethodArguments()); 41 | } 42 | 43 | private static ValueData createValueData(Annotation a) { 44 | return a instanceof Value ? createValueData((Value)a) : createValueDataFromStereotype(a); 45 | } 46 | 47 | 48 | private static ValueData createValueData(Value v) { 49 | return new ValueData(v.name(), v.value(), v.type(), v.factory(), v.factoryMethod(), new Object[0], new Object[0]); //, v.factoryMethod().isEmpty() ? new Object[0] : new Object[] {v.value()}); 50 | } 51 | 52 | 53 | private static ValueData createValueDataFromStereotype(Annotation a) { 54 | //Value v = a instanceof Value ? (Value)a : a.annotationType().getAnnotation(Value.class); 55 | Value[] values = a instanceof Value ? new Value[] {(Value)a} : a.annotationType().getAnnotationsByType(Value.class); 56 | Value v = values.length > 0 ? values[0] : null; 57 | 58 | final String name; 59 | final Object value; 60 | final Class type; 61 | final Class factory; 62 | final Object[] factoryArguments; 63 | final Object[] factoryMethodArguments; 64 | final String factoryMethod; 65 | if (v == null) { 66 | name = get(a, a, "name"); 67 | Method valueMethod = method(a.annotationType(), "value"); 68 | Class valueReturnType = valueMethod.getReturnType(); 69 | value = invoke(a, valueMethod); 70 | 71 | type = valueReturnType.isArray() ? valueReturnType.getComponentType() : valueReturnType; 72 | factory = type; 73 | factoryArguments = new Object[0]; 74 | factoryMethodArguments = new Object[0]; 75 | factoryMethod = ""; 76 | } else { 77 | name = get(v, a, "name"); 78 | value = get(v, a, "value"); 79 | factory = v.factory(); 80 | factoryArguments = Arrays.stream(values).filter(v1 -> v1.name().equals("factoryArgument")) 81 | .map(p -> p.value()[0]) 82 | .map(arg -> deref(arg, a)).toArray(Object[]::new); 83 | 84 | factoryMethod = v.factoryMethod(); 85 | String[] factoryMethodStringArguments = Arrays.stream(a.annotationType().getAnnotationsByType(Value.class)) 86 | .filter(v1 -> v1.name().equals("factoryMethodArgument")) 87 | .map(p -> p.value()[0]).toArray(String[]::new); 88 | if (!v.factoryMethod().isEmpty() && factoryMethodStringArguments.length == 0) { 89 | factoryMethodStringArguments = v.value().length > 0 ? v.value() : new String[]{"${value}"}; 90 | } 91 | 92 | factoryMethodArguments = Arrays.stream(factoryMethodStringArguments).map(arg -> deref(arg, a)).toArray(); 93 | type = v.type(); 94 | } 95 | 96 | return new ValueData(name, value, type, factory, factoryMethod, factoryArguments, factoryMethodArguments); 97 | } 98 | 99 | 100 | 101 | private static T get(Annotation meta, Annotation a, String method) { 102 | T res = invoke(meta, method(meta.annotationType(), method)); 103 | return res.getClass().isArray() ? deref(((String[])res)[0], a) : deref((String)res, a); 104 | } 105 | 106 | 107 | @SuppressWarnings("unchecked") 108 | private static T deref(String metaValue, Annotation a) { 109 | if (metaValue.startsWith("${") && metaValue.endsWith("}")) { 110 | String method = metaValue.substring(2, metaValue.length() - 1); 111 | Object dereferenced = invoke(a, method(a.annotationType(), method)); //TODO: find @Value annotation (factory method or factory argument) with value=${metaValue} and call createValueDataFromStereotype for it 112 | return (T)dereferenced; 113 | } 114 | return (T)metaValue; 115 | } 116 | 117 | 118 | 119 | static Method method(Class clazz, String name) { 120 | try { 121 | return clazz.getMethod(name); 122 | } catch (NoSuchMethodException e) { 123 | throw new IllegalStateException(e); 124 | } 125 | } 126 | 127 | @SuppressWarnings("unchecked") 128 | static T invoke(Object obj, Method method, Object... args) { 129 | try { 130 | method.setAccessible(true); 131 | return (T)method.invoke(obj, args); 132 | } catch (ReflectiveOperationException e) { 133 | throw new IllegalStateException(e); 134 | } 135 | } 136 | 137 | static boolean isContainer(Annotation a) { 138 | Method value; 139 | try { 140 | value = a.annotationType().getMethod("value"); 141 | } catch (NoSuchMethodException e) { 142 | return false; // bad practice, but so short... 143 | } 144 | Class returnType = value.getReturnType(); 145 | return returnType.isArray() && returnType.getComponentType().isAnnotation() && 146 | Arrays.stream(returnType.getComponentType().getAnnotations()).anyMatch(a2 -> Argument.class.equals(a2.annotationType())); 147 | 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/Value.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Repeatable; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Argument 10 | @Retention(RetentionPolicy.RUNTIME) 11 | @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD}) 12 | @Repeatable(Values.class) 13 | public @interface Value { 14 | String name(); 15 | String[] value(); 16 | Class type() default String.class; 17 | Class factory() default String.class; 18 | String factoryMethod() default ""; // default for ConstructorFactory that implements Function 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/ValueData.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.reflect.Array; 4 | import java.lang.reflect.Constructor; 5 | import java.lang.reflect.Method; 6 | import java.lang.reflect.Modifier; 7 | import java.util.Arrays; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | class ValueData { 12 | private final String name; 13 | private final Object value; 14 | private final Class type; 15 | private final Class factory; 16 | private final String factoryMethod; 17 | private final Object[] factoryArguments; 18 | private final Object[] factoryMethodArguments; 19 | 20 | ValueData(String name, Object value, Class type, Class factory, String factoryMethod, Object[] factoryArguments, Object[] factoryMethodArguments) { 21 | this.name = name; 22 | this.value = value; 23 | this.type = type; 24 | this.factory = factory; 25 | this.factoryMethod = factoryMethod; 26 | this.factoryArguments = factoryArguments; 27 | this.factoryMethodArguments = factoryMethodArguments; 28 | } 29 | 30 | T createInstance(Class type) { 31 | try { 32 | return createInstanceStrategy(type); 33 | } catch (ReflectiveOperationException e) { 34 | throw new IllegalStateException(e); 35 | } 36 | } 37 | 38 | @SuppressWarnings("unchecked") // too many castings... 39 | private T createInstanceStrategy(Class fieldType) throws ReflectiveOperationException { 40 | Class creator = factory == null ? type : factory; 41 | if (!"".equals(factoryMethod)) { 42 | Object f = null; 43 | Method m = findMethod(creator, factoryMethod, Arrays.stream(factoryMethodArguments).map(Object::getClass).toArray(Class[]::new)); 44 | if (!Modifier.isStatic(m.getModifiers()) || factoryArguments.length > 0) { 45 | Constructor constructor = creator.getConstructor(Arrays.stream(factoryArguments).map(Object::getClass).toArray(Class[]::new)); 46 | f = constructor.newInstance(factoryArguments); 47 | } 48 | return (T)m.invoke(f, factoryMethodArguments); 49 | } 50 | 51 | 52 | if (value.getClass().isArray() && fieldType.isArray() && isAssignable(type, value.getClass().getComponentType())) { 53 | return (T)value; 54 | } 55 | if (value.getClass().isArray() && Array.getLength(value) == 1 && isAssignable(type, Array.get(value, 0).getClass())) { 56 | return (T)Array.get(value, 0); 57 | } 58 | 59 | if (!value.getClass().isArray() && isAssignable(type, value.getClass())) { 60 | return (T)value; 61 | } 62 | 63 | Constructor constructor = creator.getConstructor(Arrays.stream(factoryArguments).map(Object::getClass).toArray(Class[]::new)); 64 | return (T)constructor.newInstance(factoryArguments); 65 | } 66 | 67 | 68 | private static Method findMethod(Class clazz, String name, Class[] paramTypes) { 69 | try { 70 | return clazz.getMethod(name, paramTypes); 71 | } catch (NoSuchMethodException e) { 72 | return Arrays.stream(clazz.getMethods()) 73 | .filter(m -> m.getName().equals(name)) 74 | .filter(m -> m.getParameterCount() == paramTypes.length) 75 | .filter(m -> areAssignable(m.getParameterTypes(), paramTypes)) 76 | .findFirst() 77 | .orElseThrow(() -> new NoSuchMethodError(String.format("%s.%s(%s)", clazz, name, Arrays.toString(paramTypes)))); //TODO: is it good to throw error? 78 | } 79 | } 80 | 81 | 82 | 83 | private static final Map primitiveWrapper = new HashMap<>(); 84 | static { 85 | primitiveWrapper.put(byte.class, Byte.class); 86 | primitiveWrapper.put(short.class, Short.class); 87 | primitiveWrapper.put(int.class, Integer.class); 88 | primitiveWrapper.put(long.class, Long.class); 89 | primitiveWrapper.put(char.class, Character.class); 90 | primitiveWrapper.put(float.class, Float.class); 91 | primitiveWrapper.put(double.class, Double.class); 92 | primitiveWrapper.put(boolean.class, Boolean.class); 93 | } 94 | 95 | private static boolean isAssignable(Class left, Class right) { 96 | Class l = left; 97 | Class r = right; 98 | if ((left.isPrimitive() || right.isPrimitive()) && !(left.isPrimitive() && right.isPrimitive())) { 99 | l = primitiveWrapper.getOrDefault(left, left); 100 | r = primitiveWrapper.getOrDefault(right, right); 101 | } 102 | return l.isAssignableFrom(r); 103 | } 104 | 105 | private static boolean areAssignable(Class[] lefts, Class[] rights) { 106 | if (lefts.length != rights.length) { 107 | return false; 108 | } 109 | int n = lefts.length; 110 | for (int i = 0; i < n; i++) { 111 | if (!isAssignable(lefts[i], rights[i])) { 112 | return false; 113 | } 114 | } 115 | return true; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/org/enumus/initializer/Values.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Argument 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD}) 11 | public @interface Values { 12 | Value[] value(); 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/EnumMapValidatorTest.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import org.enumus.samples.Color; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.util.Arrays; 7 | import java.util.HashSet; 8 | import java.util.Map; 9 | import java.util.stream.Collectors; 10 | 11 | import static org.junit.jupiter.api.Assertions.assertEquals; 12 | import static org.junit.jupiter.api.Assertions.assertThrows; 13 | import static org.junit.jupiter.api.Assertions.assertTrue; 14 | 15 | class EnumMapValidatorTest { 16 | @Test 17 | void validateEmpty() { 18 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> EnumMapValidator.validate(Color.class, "Set", "colors", () -> 0, color -> false, Color::name)); 19 | assertEquals("Set is not complete: [[RED], [GREEN], [BLUE]] (colors in squire brackets are absent)", e.getMessage()); 20 | } 21 | 22 | @Test 23 | void validateFull() { 24 | EnumMapValidator.validate(Color.class, "Set", "colors", () -> Color.values().length, color -> true, Color::name); 25 | assertTrue(Color.values().length > 0); 26 | } 27 | 28 | @Test 29 | void validateFullSet() { 30 | EnumMapValidator.validateElements(Color.class, new HashSet<>(Arrays.asList(Color.values())), "Colors list"); 31 | assertTrue(Color.values().length > 0); 32 | } 33 | 34 | @Test 35 | void validateMissingSet() { 36 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> EnumMapValidator.validateElements(Color.class, new HashSet<>(Arrays.asList(Color.RED, Color.BLUE)), "Colors list")); 37 | assertEquals("Colors list is not complete: [RED, [GREEN], BLUE] (elements in squire brackets are absent)", e.getMessage()); 38 | } 39 | 40 | @Test 41 | void validateKeysInFullMap() { 42 | Map map = Arrays.stream(Color.values()).collect(Collectors.toMap(c -> c, Enum::ordinal)); 43 | EnumMapValidator.validateKeys(Color.class, map, "Colors map"); 44 | assertEquals(Color.values().length, map.size()); 45 | } 46 | 47 | @Test 48 | void validateKeysInMissingMap() { 49 | Map map = Arrays.stream(Color.values()) 50 | .filter(c -> !Color.BLUE.equals(c)) 51 | .collect(Collectors.toMap(c -> c, Enum::ordinal)); 52 | 53 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> EnumMapValidator.validateKeys(Color.class, map, "Colors map")); 54 | assertEquals("Colors map is not complete: [RED, GREEN, [BLUE]] (keys in squire brackets are absent)", e.getMessage()); 55 | } 56 | 57 | @Test 58 | void validateValuesInFullMap() { 59 | Map map = Arrays.stream(Color.values()).collect(Collectors.toMap(Enum::name, c -> c)); 60 | EnumMapValidator.validateValues(Color.class, map, "Colors map"); 61 | } 62 | 63 | @Test 64 | void validateValuesInMissingMap() { 65 | Map map = Arrays.stream(Color.values()) 66 | .filter(c -> !Color.RED.equals(c)) 67 | .collect(Collectors.toMap(Enum::ordinal, c -> c)); 68 | 69 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> EnumMapValidator.validateValues(Color.class, map, "Colors map")); 70 | assertEquals("Colors map is not complete: [[RED], GREEN, BLUE] (values in squire brackets are absent)", e.getMessage()); 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /src/test/java/org/enumus/HierarchyTest.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import org.enumus.samples.OsType; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import static org.junit.jupiter.api.Assertions.*; 7 | 8 | class HierarchyTest { 9 | @Test 10 | void justValues() { 11 | assertTrue(OsType.values().length > 0); 12 | } 13 | 14 | @Test 15 | void parentOfRoot() { 16 | assertNull(OsType.OS.parent()); 17 | } 18 | 19 | @Test 20 | void parentOfFirstLevel() { 21 | assertEquals(OsType.OS, OsType.Windows.parent()); 22 | assertEquals(OsType.OS, OsType.Unix.parent()); 23 | } 24 | 25 | @Test 26 | void parentOfSecondLevel() { 27 | assertEquals(OsType.Windows, OsType.WindowsNT.parent()); 28 | } 29 | 30 | @Test 31 | void parentOfThirdLevel() { 32 | assertEquals(OsType.WindowsNT, OsType.WindowsNTServer.parent()); 33 | } 34 | 35 | @Test 36 | void childrenOfLeaf() { 37 | assertArrayEquals(new OsType[0], OsType.WindowsNTServer.children()); 38 | } 39 | 40 | @Test 41 | void childrenPreLeafLevel() { 42 | assertArrayEquals(new OsType[] {OsType.Linux, OsType.AIX, OsType.HpUx, OsType.SunOs}, OsType.Unix.children()); 43 | } 44 | 45 | @Test 46 | void childrenIntermediateLevel() { 47 | assertArrayEquals( 48 | new OsType[] {OsType.WindowsNT, OsType.Windows2000, OsType.WindowsXp, OsType.WindowsVista, OsType.Windows7, OsType.Windows95, OsType.Windows98,}, 49 | OsType.Windows.children()); 50 | } 51 | 52 | @Test 53 | void childrenTopLeafLevel() { 54 | assertArrayEquals(new OsType[] {OsType.Windows, OsType.Unix}, OsType.OS.children()); 55 | } 56 | 57 | @Test 58 | void callDirect() { 59 | assertTrue(OsType.Unix.supportsXWindowSystem()); 60 | } 61 | 62 | @Test 63 | void callFromChild() { 64 | assertTrue(OsType.Linux.supportsXWindowSystem()); 65 | } 66 | 67 | @Test 68 | void callNotImplemented() { 69 | assertFalse(OsType.Windows.supportsXWindowSystem()); 70 | } 71 | 72 | @Test 73 | void callRoot() { 74 | assertFalse(OsType.OS.supportsXWindowSystem()); 75 | } 76 | 77 | 78 | @Test 79 | void relation1() { 80 | assertTrue(OsType.Windows2000.isA(OsType.Windows)); 81 | assertTrue(OsType.Linux.isA(OsType.Unix)); 82 | assertFalse(OsType.Linux.isA(OsType.Windows)); 83 | } 84 | 85 | @Test 86 | void relation2() { 87 | assertTrue(OsType.Windows2000Server.isA(OsType.Windows)); 88 | assertTrue(OsType.Windows98.isA(OsType.Windows)); 89 | assertFalse(OsType.Windows98.isA(OsType.Unix)); 90 | assertFalse(OsType.Windows98.isA(OsType.Linux)); 91 | } 92 | 93 | @Test 94 | void relationSiblings() { 95 | assertFalse(OsType.Linux.isA(OsType.AIX)); 96 | assertFalse(OsType.SunOs.isA(OsType.HpUx)); 97 | assertFalse(OsType.Windows2000Server.isA(OsType.Windows2000Workstation)); 98 | } 99 | } -------------------------------------------------------------------------------- /src/test/java/org/enumus/InitializationTest.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import org.enumus.initializer.Argument; 4 | import org.enumus.initializer.BooleanValue; 5 | import org.enumus.initializer.ByteValue; 6 | import org.enumus.initializer.DateValue; 7 | import org.enumus.initializer.DoubleValue; 8 | import org.enumus.initializer.Initializable; 9 | import org.enumus.initializer.IntValue; 10 | import org.enumus.initializer.LongValue; 11 | import org.enumus.initializer.PatternValue; 12 | import org.enumus.initializer.ShortValue; 13 | import org.enumus.initializer.Value; 14 | import org.enumus.samples.OsType; 15 | import org.enumus.samples.Platform; 16 | import org.enumus.samples.Software; 17 | import org.enumus.samples.article.IsoAlpha2; 18 | import org.enumus.samples.article.enumwitannotations.Country; 19 | import org.junit.jupiter.api.Test; 20 | 21 | import java.lang.annotation.ElementType; 22 | import java.lang.annotation.Retention; 23 | import java.lang.annotation.RetentionPolicy; 24 | import java.lang.annotation.Target; 25 | import java.lang.reflect.InvocationTargetException; 26 | import java.text.ParseException; 27 | import java.text.SimpleDateFormat; 28 | import java.util.Date; 29 | import java.util.regex.Pattern; 30 | 31 | import static org.enumus.samples.OsType.Unix; 32 | import static org.enumus.samples.OsType.Windows; 33 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 34 | import static org.junit.jupiter.api.Assertions.assertEquals; 35 | import static org.junit.jupiter.api.Assertions.assertNull; 36 | import static org.junit.jupiter.api.Assertions.assertThrows; 37 | import static org.junit.jupiter.api.Assertions.assertTrue; 38 | 39 | class InitializationTest { 40 | @Test 41 | void testSoftware() { 42 | assertTrue(Software.class.getEnumConstants().length > 0); 43 | } 44 | 45 | @Test 46 | void oneNullString() { 47 | assertNull(OneStringParamTestEnum.ZERO.str); 48 | } 49 | 50 | @Test 51 | void oneStringParameterSentDirectly() { 52 | assertEquals("one", OneStringParamTestEnum.ONE.str); 53 | } 54 | 55 | @Test 56 | void oneStringParameterSentViaValueAnnotation() { 57 | assertEquals("two", OneStringParamTestEnum.TWO.str); 58 | } 59 | 60 | 61 | @Test 62 | void oneDefaultInt() { 63 | assertEquals(0, OneIntParamTestEnum.ZERO.number); 64 | } 65 | 66 | @Test 67 | void oneIntParameterSentDirectly() { 68 | assertEquals(1, OneIntParamTestEnum.ONE.number); 69 | } 70 | 71 | @Test 72 | void oneIntParameterSentViaValueAnnotation() { 73 | assertEquals(2, OneIntParamTestEnum.TWO.number); 74 | } 75 | 76 | @Test 77 | void oneDefaultDouble() { 78 | assertEquals(0, OneDoubleParamTestEnum.ZERO.number); 79 | } 80 | @Test 81 | void oneDoubleParameterSentDirectly() { 82 | assertEquals(3.1415926, OneDoubleParamTestEnum.PI.number, 0.01); 83 | } 84 | 85 | @Test 86 | void oneDoubleParameterSentViaValueAnnotation() { 87 | assertEquals(2.718281828, OneDoubleParamTestEnum.E.number, 0.01); 88 | } 89 | 90 | 91 | @Test 92 | void oneDateParameterValues() { 93 | assertTrue(OneDateParamTestEnum.values().length > 0); 94 | } 95 | 96 | @Test 97 | void oneDateParameterArgument() { 98 | assertEquals(date("1917-11-07"), OneDateParamTestEnum.AURORA.date); 99 | } 100 | 101 | @Test 102 | void oneDateParameterAnnotation() { 103 | assertEquals(date("1789-07-14"), OneDateParamTestEnum.BASTILLE.date); 104 | } 105 | 106 | @Test 107 | void onePatternParameterValues() { 108 | assertTrue(OnePatternTestEnum.values().length > 0); 109 | } 110 | 111 | @Test 112 | void onePatternParameterArgument() { 113 | assertTrue(OnePatternTestEnum.DIGITS.pattern.matcher("12345").find()); 114 | } 115 | 116 | @Test 117 | void onePatternParameterAnnotation() { 118 | assertTrue(OnePatternTestEnum.IP.pattern.matcher("127.0.0.1").find()); 119 | } 120 | 121 | @Test 122 | void notEnum() { 123 | assertThrows(IllegalStateException.class, MyTestClass::new, String.format("Class %s is not an enum", MyTestClass.class.getName())); 124 | } 125 | 126 | @Test 127 | void byteArray() { 128 | assertArrayEquals(new byte[] {1, 2, 3}, ArrayArgumentEnum.BYTE.getBytearr()); 129 | } 130 | 131 | @Test 132 | void shortArray() { 133 | assertArrayEquals(new short[] {1, 2, 3}, ArrayArgumentEnum.SHORT.getShortarr()); 134 | } 135 | 136 | @Test 137 | void intArray() { 138 | assertArrayEquals(new int[] {1, 2, 3}, ArrayArgumentEnum.INT.getIntarr()); 139 | } 140 | 141 | @Test 142 | void longArray() { 143 | assertArrayEquals(new long[] {11111111111L, 2222222222L, 3333333333L}, ArrayArgumentEnum.LONG.getLongarr()); 144 | } 145 | 146 | @Test 147 | void stringArray() { 148 | assertArrayEquals(new String[] {"red", "green", "blue"}, ArrayArgumentEnum.STRING.getStrarr()); 149 | } 150 | 151 | @Test 152 | void booleanArray() { 153 | assertArrayEquals(new boolean[] {true, false}, ArrayArgumentEnum.BOOLEAN.getBoolarr()); 154 | } 155 | 156 | @Test 157 | void enumArray() { 158 | assertArrayEquals(new OsType[] {Windows, Unix}, ArrayArgumentEnum.WINDOWS_UNIX.getOperatingSystems()); 159 | } 160 | 161 | @Test 162 | void countriesArray() { 163 | assertArrayEquals(new Country[] {Country.ENGLAND, Country.WELSH, Country.SCOTLAND}, Country.UNITED_KINDOM.getFederatedState()); 164 | assertEquals(IsoAlpha2.GB, Country.UNITED_KINDOM.getIso()); 165 | } 166 | 167 | //TODO: this test should throw exception 168 | @Test 169 | void wrongNameInAnnotation() { 170 | assertTrue(WrongArgumentNameEnum.values().length > 0); 171 | } 172 | 173 | @Test 174 | void wrongDateFormat() { 175 | ExceptionInInitializerError e = assertThrows(ExceptionInInitializerError.class, WrongAnnotationEnum::values); 176 | assertEquals(IllegalStateException.class, e.getCause().getClass()); 177 | assertEquals(InvocationTargetException.class, e.getCause().getCause().getClass()); 178 | assertEquals(IllegalArgumentException.class, e.getCause().getCause().getCause().getClass()); 179 | } 180 | 181 | @Test 182 | void wrongArgumentType() { 183 | NoSuchMethodError e = assertThrows(NoSuchMethodError.class, WrongArgType::values); 184 | assertTrue(e.getMessage().contains("parse")); 185 | } 186 | 187 | @Test 188 | void wrongNumberOfArguements() { 189 | ExceptionInInitializerError e = assertThrows(ExceptionInInitializerError.class, WrongNumberOfArguments::values); 190 | assertEquals(IllegalStateException.class, e.getCause().getClass()); 191 | assertEquals(NoSuchMethodException.class, e.getCause().getCause().getClass()); 192 | } 193 | 194 | @Test 195 | void wrongNumberOfArguementsOfFactoryMethod() { 196 | ExceptionInInitializerError e = assertThrows(ExceptionInInitializerError.class, WrongNumberOfArguments2::values); 197 | assertEquals(IllegalStateException.class, e.getCause().getClass()); 198 | assertEquals(NoSuchMethodException.class, e.getCause().getCause().getClass()); 199 | } 200 | 201 | 202 | public enum OneStringParamTestEnum implements Initializable { 203 | ZERO(), 204 | ONE("one"), 205 | 206 | @Value(name = "str", value = "two") 207 | TWO(),; 208 | 209 | private final String str; 210 | 211 | OneStringParamTestEnum() { 212 | str = $(); 213 | } 214 | OneStringParamTestEnum(String str) { 215 | this.str = str; 216 | } 217 | } 218 | 219 | public enum OneIntParamTestEnum implements Initializable { 220 | ZERO(), 221 | ONE(1), 222 | 223 | @IntValue(name = "number", value = 2) 224 | TWO(), 225 | ; 226 | 227 | private final int number; 228 | 229 | OneIntParamTestEnum() { 230 | number = $(); 231 | } 232 | OneIntParamTestEnum(int number) { 233 | this.number = number; 234 | } 235 | } 236 | 237 | public enum OneDoubleParamTestEnum implements Initializable { 238 | ZERO(), 239 | PI(3.1415926), 240 | 241 | @DoubleValue(name = "number", value = 2.718281828) 242 | E(), 243 | ; 244 | 245 | private final double number; 246 | 247 | OneDoubleParamTestEnum() { 248 | number = $(); 249 | } 250 | OneDoubleParamTestEnum(double number) { 251 | this.number = number; 252 | } 253 | } 254 | 255 | public enum OneDateParamTestEnum implements Initializable { 256 | @DateValue(name = "date", value = "1789-07-14", format = "yyyy-MM-dd") 257 | BASTILLE(), 258 | AURORA(date("1917-11-07")), 259 | ; 260 | 261 | private final Date date; 262 | 263 | OneDateParamTestEnum(Date date) { 264 | this.date = date; 265 | } 266 | 267 | OneDateParamTestEnum() { 268 | this.date = $(); 269 | } 270 | } 271 | 272 | 273 | public enum OnePatternTestEnum implements Initializable { 274 | DIGITS(Pattern.compile("^\\d+$")), 275 | 276 | @PatternValue(name = "pattern", regex = "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$") 277 | IP(), 278 | 279 | @PatternValue(name = "pattern", regex = "hello", options = Pattern.CASE_INSENSITIVE) 280 | CASE_INSENSITIVE(), 281 | ; 282 | 283 | private final Pattern pattern; 284 | 285 | OnePatternTestEnum(Pattern pattern) { 286 | this.pattern = pattern; 287 | } 288 | 289 | OnePatternTestEnum() { 290 | pattern = $(); 291 | } 292 | } 293 | 294 | 295 | public enum ArrayArgumentEnum implements Initializable { 296 | @ByteValue(name = "bytearr", value = {1, 2, 3}) 297 | BYTE, 298 | @ShortValue(name = "shortarr", value = {1, 2, 3}) 299 | SHORT, 300 | @IntValue(name = "intarr", value = {1, 2, 3}) 301 | INT, 302 | @LongValue(name = "longarr", value = {11111111111L, 2222222222L, 3333333333L}) 303 | LONG, 304 | @BooleanValue(name = "boolarr", value = {true, false}) 305 | BOOLEAN, 306 | @Value(name = "strarr", value = {"red", "green", "blue"}) 307 | STRING, 308 | 309 | 310 | @Platform(name = "operatingSystems", os = {Windows, Unix}) 311 | WINDOWS_UNIX, 312 | 313 | ; 314 | 315 | private byte[] bytearr; 316 | private short[] shortarr; 317 | private int[] intarr; 318 | private long[] longarr; 319 | private boolean[] boolarr; 320 | private String[] strarr; 321 | private OsType[] operatingSystems; 322 | 323 | 324 | ArrayArgumentEnum() { 325 | this.bytearr = argument(); 326 | this.shortarr = argument(); 327 | this.intarr = argument(); 328 | this.longarr = argument(); 329 | this.boolarr = argument(); 330 | this.strarr = argument(); 331 | this.operatingSystems = argument(); 332 | } 333 | 334 | public byte[] getBytearr() { 335 | return bytearr; 336 | } 337 | 338 | public short[] getShortarr() { 339 | return shortarr; 340 | } 341 | 342 | public int[] getIntarr() { 343 | return intarr; 344 | } 345 | 346 | public long[] getLongarr() { 347 | return longarr; 348 | } 349 | 350 | public boolean[] getBoolarr() { 351 | return boolarr; 352 | } 353 | 354 | public String[] getStrarr() { 355 | return strarr; 356 | } 357 | 358 | public OsType[] getOperatingSystems() { 359 | return operatingSystems; 360 | } 361 | } 362 | 363 | class MyTestClass implements Initializable { 364 | MyTestClass() { 365 | $(); 366 | } 367 | } 368 | 369 | private static Date date(String str) { 370 | try { 371 | return new SimpleDateFormat("yyyy-MM-dd").parse(str); 372 | } catch (ParseException e) { 373 | throw new IllegalArgumentException(str, e); 374 | } 375 | } 376 | 377 | enum WrongArgumentNameEnum implements Initializable { 378 | @Value(name = "string", value = "wrong") 379 | ONE(); 380 | 381 | @SuppressWarnings("unused") // this is failure test; the field cannot be used 382 | private final String str; 383 | 384 | WrongArgumentNameEnum() { 385 | this.str = argument(); 386 | } 387 | } 388 | 389 | 390 | enum WrongAnnotationEnum implements Initializable { 391 | @DateValue(name = "date", value = "1789-07-14", format = "wrong format") 392 | WRONG_DATE_FORMAT(), 393 | ; 394 | 395 | @SuppressWarnings("unused") // this is failure test; the field cannot be used 396 | private final Date date; 397 | 398 | WrongAnnotationEnum() { 399 | this.date = argument(); 400 | } 401 | } 402 | 403 | 404 | @Argument 405 | @Retention(RetentionPolicy.RUNTIME) 406 | @Target(ElementType.FIELD) 407 | @Value(name = "${name}", value = "${value}", type = Date.class, factory = SimpleDateFormat.class, factoryMethod = "parse") 408 | @Value(name = "factoryArgument", value = "${format}") 409 | public @interface WrongDateValue { 410 | String name(); 411 | int value(); // wrong type 412 | String format() default "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // example: 2001-07-04T12:08:56.235-0700 413 | } 414 | 415 | 416 | enum WrongArgType implements Initializable { 417 | @WrongDateValue(name = "date", value = 17890714, format = "yyyyMMdd") 418 | WRONG_DATE_TYPE(), 419 | ; 420 | 421 | @SuppressWarnings("unused") // this is failure test; the field cannot be used 422 | private final Date date; 423 | 424 | WrongArgType() { 425 | this.date = argument(); 426 | } 427 | } 428 | 429 | 430 | 431 | @Argument 432 | @Retention(RetentionPolicy.RUNTIME) 433 | @Target(ElementType.FIELD) 434 | @Value(name = "${name}", value = "${value}", type = Date.class, factory = SimpleDateFormat.class, factoryMethod = "parse") 435 | @Value(name = "factoryArgument", value = "${format}") 436 | @Value(name = "factoryArgument", value = "${format2}") 437 | public @interface ExtraArgumentDateValue { 438 | String name(); 439 | String value(); 440 | String format() default "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // example: 2001-07-04T12:08:56.235-0700 441 | String format2() default "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // example: 2001-07-04T12:08:56.235-0700 442 | } 443 | 444 | enum WrongNumberOfArguments implements Initializable { 445 | @ExtraArgumentDateValue(name = "date", value = "17890714", format = "yyyyMMdd", format2 = "yyyyMMdd") 446 | DATE(), 447 | ; 448 | 449 | @SuppressWarnings("unused") // this is failure test; the field cannot be used 450 | private final Date date; 451 | 452 | WrongNumberOfArguments() { 453 | this.date = argument(); 454 | } 455 | } 456 | 457 | 458 | @Argument 459 | @Retention(RetentionPolicy.RUNTIME) 460 | @Target(ElementType.FIELD) 461 | @Value(name = "${name}", value = "${value}", type = Date.class, factory = SimpleDateFormat.class, factoryMethod = "parse") 462 | @Value(name = "factoryArgument", value = "${format}") 463 | @Value(name = "factoryArgument", value = "${format2}") 464 | public @interface ExtraArgumentParseDateValue { 465 | String name(); 466 | String[] value(); 467 | String format() default "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // example: 2001-07-04T12:08:56.235-0700 468 | } 469 | 470 | enum WrongNumberOfArguments2 implements Initializable { 471 | @ExtraArgumentParseDateValue(name = "date", value = {"17890714", "17890714"}, format = "yyyyMMdd") 472 | DATE(), 473 | ; 474 | 475 | @SuppressWarnings("unused") // this is failure test; the field cannot be used 476 | private final Date date; 477 | 478 | WrongNumberOfArguments2() { 479 | this.date = argument(); 480 | } 481 | } 482 | } 483 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/MirrorTest.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import org.enumus.samples.Color; 4 | import org.enumus.samples.Color2; 5 | import org.enumus.samples.RainbowColors1; 6 | import org.enumus.samples.Rgb; 7 | import org.enumus.samples.Shade; 8 | import org.junit.jupiter.api.Test; 9 | 10 | import static java.lang.String.format; 11 | import static org.junit.jupiter.api.Assertions.assertEquals; 12 | import static org.junit.jupiter.api.Assertions.assertNotNull; 13 | import static org.junit.jupiter.api.Assertions.assertThrows; 14 | import static org.junit.jupiter.api.Assertions.assertTrue; 15 | 16 | class MirrorTest { 17 | @Test 18 | void goodMirror() { 19 | // trivial assertions just to touch the enum Color 20 | assertNotNull(Rgb.RED); 21 | assertNotNull(Rgb.GREEN); 22 | assertNotNull(Rgb.BLUE); 23 | } 24 | 25 | @Test 26 | void fieldWithWrongCase() { 27 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> Mirror.mirrors(Color.class, Color2.class)); 28 | assertEquals(format("Element #2 of mirror %s.%s does not reflect the source %s.%s", Color2.class.getName(), Color2.Blue.name(), Color.class.getName(), Color.BLUE.name()), e.getMessage()); 29 | } 30 | 31 | @Test 32 | void goodMultipleMirrors() { 33 | Mirror.mirrors(RainbowColors1.class, Color.class, Shade.class); 34 | assertEquals(RainbowColors1.values().length, Color.values().length + Shade.values().length); 35 | } 36 | 37 | 38 | @Test 39 | void missingMirrors() { 40 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> Mirror.mirrors(RainbowColors1.class, Color.class)); 41 | assertTrue(e.getMessage().contains("Source and mirror enums have different number of elements")); 42 | } 43 | 44 | @Test 45 | void discoverCaller() { 46 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> Mirror.of(Color.class)); 47 | assertEquals(format("Caller of Mirror.of() %s is not enum", getClass().getName()), e.getMessage()); 48 | } 49 | 50 | @Test 51 | void mirrorOfItself() { 52 | ExceptionInInitializerError e = assertThrows(ExceptionInInitializerError.class, TestEnum::values); 53 | assertEquals(format("Class %s cannot be mirror of itself", TestEnum.class.getName()), e.getCause().getMessage()); 54 | } 55 | 56 | enum TestEnum { 57 | ONE; 58 | static { 59 | Mirror.of(TestEnum.class); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/test/java/org/enumus/ValueOfTest.java: -------------------------------------------------------------------------------- 1 | package org.enumus; 2 | 3 | import org.enumus.samples.MathConstant; 4 | import org.enumus.samples.Rgb; 5 | import org.junit.jupiter.api.Test; 6 | 7 | import static java.lang.String.format; 8 | import static org.junit.jupiter.api.Assertions.assertEquals; 9 | import static org.junit.jupiter.api.Assertions.assertThrows; 10 | 11 | class ValueOfTest { 12 | @Test 13 | void valueOfInt() { 14 | assertEquals(Rgb.RED, Rgb.valueOfMin(635)); 15 | assertEquals(Rgb.RED, Rgb.valueOfMax(700)); 16 | } 17 | 18 | 19 | @Test 20 | void valueOfWrongValue() { 21 | IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Rgb.valueOfMax(123)); 22 | assertEquals(format("No enum constant %s.%d", Rgb.class.getName(), 123), e.getMessage()); 23 | } 24 | 25 | 26 | @Test 27 | void approximateExact() { 28 | assertEquals(MathConstant.PI, MathConstant.approximateValueOf(MathConstant.PI.value())); 29 | } 30 | 31 | @Test 32 | void approximate() { 33 | assertEquals(MathConstant.PI, MathConstant.approximateValueOf(3.14)); 34 | } 35 | 36 | @Test 37 | void approximateWrong() { 38 | IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> MathConstant.approximateValueOf(3)); 39 | assertEquals(format("No enum constant %s.%.1f", MathConstant.class.getName(), 3.0), e.getMessage()); 40 | } 41 | 42 | @Test 43 | void inRange() { 44 | assertEquals(Rgb.RED, Rgb.valueByWaveLength(650)); 45 | } 46 | 47 | @Test 48 | void rangeFloor() { 49 | assertEquals(Rgb.GREEN, Rgb.valueByWaveLength(520)); 50 | } 51 | 52 | @Test 53 | void rangeCeiling() { 54 | assertEquals(Rgb.BLUE, Rgb.valueByWaveLength(490)); 55 | } 56 | 57 | @Test 58 | void betweenRanges() { 59 | IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Rgb.valueByWaveLength(500)); 60 | assertEquals(format("No enum constant %s.%d", Rgb.class.getName(), 500), e.getMessage()); 61 | } 62 | 63 | @Test 64 | void caseInsensitiveExactCase() { 65 | assertEquals(Rgb.GREEN, Rgb.caseInsensitiveValueOf("GREEN")); 66 | } 67 | 68 | @Test 69 | void caseInsensitiveOppositeCase() { 70 | assertEquals(Rgb.RED, Rgb.caseInsensitiveValueOf("red")); 71 | } 72 | 73 | @Test 74 | void caseInsensitiveMixedCase() { 75 | assertEquals(Rgb.BLUE, Rgb.caseInsensitiveValueOf("BluE")); 76 | } 77 | 78 | @Test 79 | void caseInsensitiveNoMatch() { 80 | IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Rgb.caseInsensitiveValueOf("Black")); 81 | assertEquals(format("No enum constant %s.%s", Rgb.class.getName(), "Black"), e.getMessage()); 82 | } 83 | 84 | @Test 85 | void outOfRangeTooLow() { 86 | IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Rgb.valueByWaveLength(1)); 87 | assertEquals("No enum constant org.enumus.samples.Rgb.1", e.getMessage()); 88 | } 89 | 90 | @Test 91 | void outOfRangeTooHigh() { 92 | IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Rgb.valueByWaveLength(999)); 93 | assertEquals("No enum constant org.enumus.samples.Rgb.999", e.getMessage()); 94 | } 95 | } -------------------------------------------------------------------------------- /src/test/java/org/enumus/initializer/UtilTest.java: -------------------------------------------------------------------------------- 1 | package org.enumus.initializer; 2 | 3 | import org.enumus.samples.Color; 4 | import org.enumus.samples.Environment; 5 | import org.enumus.samples.Platform; 6 | import org.enumus.samples.Software; 7 | import org.junit.jupiter.api.Test; 8 | 9 | import java.lang.annotation.Annotation; 10 | import java.lang.reflect.InvocationTargetException; 11 | import java.util.Arrays; 12 | 13 | import static org.junit.jupiter.api.Assertions.assertArrayEquals; 14 | import static org.junit.jupiter.api.Assertions.assertEquals; 15 | import static org.junit.jupiter.api.Assertions.assertNotNull; 16 | import static org.junit.jupiter.api.Assertions.assertThrows; 17 | import static org.junit.jupiter.api.Assertions.assertTrue; 18 | 19 | class UtilTest { 20 | @Test 21 | void nameOfEnumConstant() { 22 | assertEquals(Color.RED.name(), Util.name(Color.RED)); 23 | } 24 | 25 | @Test 26 | void nameOfNotEnum() { 27 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> Util.name(this)); 28 | assertEquals(NoSuchMethodException.class, e.getCause().getClass()); 29 | } 30 | 31 | @Test 32 | void noAnnotations() { 33 | assertArrayEquals(new Annotation[0], Util.annotations(Color.RED, Color.RED.name())); 34 | } 35 | 36 | @Test 37 | void annotations() { 38 | Annotation[] annotations = Util.annotations(Software.INTELLIJ, Software.INTELLIJ.name()); 39 | assertNotNull(annotations); 40 | assertEquals(3, annotations.length); 41 | assertArrayEquals(new Class[] {Value.class, Platform.class, Environment.class}, Arrays.stream(annotations).map(Annotation::annotationType).toArray(Class[]::new)); 42 | } 43 | 44 | @Test 45 | void noName() { 46 | IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Util.annotations(Color.RED, "red")); 47 | assertTrue(e.getMessage().startsWith("Field red does not exist")); 48 | } 49 | 50 | @Test 51 | void goodMethod() { 52 | assertEquals("toString", Util.method(getClass(), "toString").getName()); 53 | } 54 | 55 | @Test 56 | void methodDoesNotExist() { 57 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> Util.method(getClass(), "doesNotExist")); 58 | assertEquals(NoSuchMethodException.class, e.getCause().getClass()); 59 | } 60 | 61 | @Test 62 | void goodInvoke() throws NoSuchMethodException { 63 | assertEquals("lo", Util.invoke("hello", String.class.getMethod("substring", int.class), 3)); 64 | } 65 | 66 | @Test 67 | void wrongArgumentTypeInvoke() { 68 | // integer argument is expected but string is provided 69 | IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Util.invoke("hello", String.class.getMethod("substring", int.class), "3")); 70 | assertEquals("argument type mismatch", e.getMessage()); 71 | } 72 | 73 | @Test 74 | void npeInvoke() { 75 | assertThrows(NullPointerException.class, () -> Util.invoke(null, String.class.getMethod("substring", int.class), 3)); 76 | } 77 | 78 | @Test 79 | void badInvoke() { 80 | IllegalStateException e = assertThrows(IllegalStateException.class, () -> Util.invoke("hello", String.class.getMethod("substring", int.class), -1)); 81 | assertEquals(InvocationTargetException.class, e.getCause().getClass()); 82 | assertEquals(StringIndexOutOfBoundsException.class, e.getCause().getCause().getClass()); 83 | } 84 | } -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/Color.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | public enum Color { 4 | RED, GREEN, BLUE 5 | } 6 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/Color2.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | public enum Color2 { 4 | RED, GREEN, Blue 5 | } 6 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/Environment.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | import org.enumus.initializer.Argument; 4 | 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | @Retention(RetentionPolicy.RUNTIME) 11 | @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD}) 12 | @Argument 13 | public @interface Environment { 14 | String name(); 15 | RuntimeEnvironment[] value(); 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/ManualColor.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | import java.util.Arrays; 4 | import java.util.Map; 5 | import java.util.stream.Collectors; 6 | 7 | public enum ManualColor { 8 | RED("red"), GREEN("green"), BLUE("blue"),; 9 | 10 | private final String title; 11 | private static final Map titles = Arrays.stream(ManualColor.values()).collect(Collectors.toMap(ManualColor::getTitle, e -> e)); 12 | 13 | ManualColor(String title) { 14 | this.title = title; 15 | } 16 | 17 | public String getTitle() { 18 | return title; 19 | } 20 | 21 | public static ManualColor valueOfTitle(String title) { 22 | return titles.get(title); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/MathConstant.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | import org.enumus.ValueOf; 4 | 5 | public enum MathConstant { 6 | PI(3.1415926), 7 | E(2.718281828), 8 | ; 9 | private final double value; 10 | private static ValueOf approximately = new ValueOf<>(MathConstant.class, e -> e.value, (v1, v2) -> { 11 | double diff = Math.abs(v1 - v2); 12 | return diff < 0.01 ? 0 : diff < 0 ? -1 : 1; 13 | }); 14 | 15 | MathConstant(double value) { 16 | this.value = value; 17 | } 18 | 19 | public static MathConstant approximateValueOf(double value) { 20 | return approximately.valueOf(value); 21 | } 22 | 23 | public double value() { 24 | return value; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/OsType.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | import org.enumus.Hierarchy; 4 | 5 | public enum OsType { 6 | OS(null), 7 | Windows(OS), 8 | WindowsNT(Windows), 9 | WindowsNTWorkstation(WindowsNT), 10 | WindowsNTServer(WindowsNT), 11 | Windows2000(Windows), 12 | Windows2000Server(Windows2000), 13 | Windows2000Workstation(Windows2000), 14 | WindowsXp(Windows), 15 | WindowsVista(Windows), 16 | Windows7(Windows), 17 | Windows95(Windows), 18 | Windows98(Windows), 19 | Unix(OS) { 20 | @Override 21 | public boolean supportsXWindowSystem() { 22 | return true; 23 | } 24 | }, 25 | Linux(Unix), 26 | IOS(Linux), 27 | Android(Linux), 28 | AIX(Unix), 29 | HpUx(Unix), 30 | SunOs(Unix), 31 | ; 32 | 33 | private OsType parent; 34 | private static Hierarchy hierarchy = new Hierarchy<>(OsType.class, e -> e.parent); 35 | 36 | 37 | OsType(OsType parent) { 38 | this.parent = parent; 39 | } 40 | 41 | public OsType parent() { 42 | return parent; 43 | } 44 | 45 | public OsType[] children() { 46 | return hierarchy.getChildren(this); 47 | } 48 | 49 | public boolean supportsXWindowSystem() { 50 | return hierarchy.invoke(this, args -> false); 51 | } 52 | 53 | public boolean isA(OsType other) { 54 | return hierarchy.relate(other, this); 55 | } 56 | } -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/Platform.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | import org.enumus.initializer.Argument; 4 | import org.enumus.initializer.Value; 5 | 6 | import java.lang.annotation.ElementType; 7 | import java.lang.annotation.Retention; 8 | import java.lang.annotation.RetentionPolicy; 9 | import java.lang.annotation.Target; 10 | 11 | @Retention(RetentionPolicy.RUNTIME) 12 | @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD}) 13 | //@Value(name = "${name}", value = "${os}", type = OsType.class, factory = OsType.class, factoryMethod = "valueOf") 14 | @Value(name = "${name}", value = "${os}", type = OsType.class, factory = OsType.class) 15 | //@Value(name = "factoryMethodArgument", value = "${os}") 16 | @Argument 17 | public @interface Platform { 18 | String name(); 19 | OsType[] os(); 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/RainbowColors1.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | /** 4 | * Created by alexander on 12/14/18. 5 | */ 6 | public enum RainbowColors1 { 7 | RED, GREEN, BLUE, VIOLET, ORANGE, YELLOW 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/Rgb.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | import org.enumus.Mirror; 4 | import org.enumus.ValueOf; 5 | import org.enumus.ValueOfRange; 6 | 7 | public enum Rgb { 8 | RED(635, 700), 9 | GREEN(520, 560), 10 | BLUE(450, 490), 11 | ; 12 | 13 | private static final ValueOf minimum = new ValueOf<>(Rgb.class, e -> e.min); 14 | private static final ValueOf maximum = new ValueOf<>(Rgb.class, e -> e.max); 15 | private static final ValueOfRange waveLength = new ValueOfRange<>(Rgb.class, e -> e.min, e -> e.max); 16 | private static final ValueOf caseInsensitive = new ValueOf<>(Rgb.class, Enum::name, String.CASE_INSENSITIVE_ORDER); 17 | static { 18 | Mirror.of(Color.class); 19 | } 20 | 21 | /** 22 | * min wavelength, nm 23 | */ 24 | private final int min; 25 | 26 | /** 27 | * max wavelength, nm 28 | */ 29 | private final int max; 30 | 31 | Rgb(int min, int max) { 32 | this.min = min; 33 | this.max = max; 34 | } 35 | 36 | public int min() { 37 | return min; 38 | } 39 | 40 | public int max() { 41 | return max; 42 | } 43 | 44 | 45 | public static Rgb valueOfMin(int value) { 46 | return minimum.valueOf(value); 47 | } 48 | 49 | public static Rgb valueOfMax(int value) { 50 | return maximum.valueOf(value); 51 | } 52 | 53 | public static Rgb valueByWaveLength(int wave) { 54 | return waveLength.valueOf(wave); 55 | } 56 | 57 | public static Rgb caseInsensitiveValueOf(String name) { 58 | return caseInsensitive.valueOf(name); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/RuntimeEnvironment.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | /** 4 | * Created by alexander on 12/17/18. 5 | */ 6 | public enum RuntimeEnvironment { 7 | JAVA, 8 | DOTNET, 9 | NODEJS, 10 | PYTHON, 11 | PERL, 12 | } 13 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/Shade.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | /** 4 | * Created by alexander on 12/14/18. 5 | */ 6 | public enum Shade { 7 | VIOLET, ORANGE, YELLOW 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/Software.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples; 2 | 3 | import org.enumus.initializer.Initializable; 4 | import org.enumus.initializer.Value; 5 | 6 | import static org.enumus.samples.OsType.Unix; 7 | import static org.enumus.samples.OsType.Windows; 8 | 9 | public enum Software implements Initializable { 10 | MS_WORD("Microsoft Word", "Microsoft Office", "HKLM/Microsoft/Office/Word", "/Program Files/Microsoft Office/Microsoft Word", new OsType[] {Windows}, null), 11 | 12 | //INTELLIJ("IntelliJ IDEA", null, null, null, new OsType[] {OsType.Windows, OsType.Unix}, RuntimeEnvironment.JAVA), 13 | 14 | @Value(name = "title", value = "IntelliJ IDEA") 15 | @Platform(name = "operatingSystem", os = {Windows, Unix}) 16 | @Environment(name = "environemnt", value = RuntimeEnvironment.JAVA) 17 | INTELLIJ(){}, 18 | 19 | ECLIPSE(), 20 | ; 21 | 22 | 23 | private final String title; 24 | private final String parentTitle; 25 | private final String registryPath; 26 | private final String path; 27 | private final OsType[] operatingSystems; 28 | private final RuntimeEnvironment environment; 29 | 30 | Software() { 31 | this.title = $(); 32 | this.parentTitle = $(); 33 | this.registryPath = $(); 34 | this.path = $(); 35 | this.operatingSystems = $(); 36 | this.environment = $(); 37 | 38 | } 39 | 40 | 41 | Software(String title, String parentTitle, String registryPath, String path, OsType[] operatingSystems, RuntimeEnvironment environment) { 42 | this.title = title; 43 | this.parentTitle = parentTitle; 44 | this.registryPath = registryPath; 45 | this.path = path; 46 | this.operatingSystems = operatingSystems; 47 | this.environment = environment; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/article/IsoAlpha2.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples.article; 2 | 3 | public enum IsoAlpha2 { 4 | AD, AE, AF, AG, AI, AL, AM, AN, AO, AQ, AR, AS, AT, AU, AW, AX, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BL, BM, BN, BO, BQ, BR, BS, BT, BV, BW, BY, BZ, CA, CC, CD, CF, CG, CH, CI, CK, CL, CM, CN, CO, CR, CU, CV, CW, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, EH, ER, ES, ET, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GF, GG, GH, GI, GL, GM, GN, GP, GQ, GR, GS, GT, GU, GW, GY, HK, HM, HN, HR, HT, HU, ID, IE, IL, IM, IN, IO, IQ, IR, IS, IT, JE, JM, JO, JP, KE, KG, KH, KI, KM, KN, KP, KR, KW, KY, KZ, LA, LB, LC, LI, LK, LR, LS, LT, LU, LV, LY, MA, MC, MD, ME, MF, MG, MH, MK, ML, MM, MN, MO, MP, MQ, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NF, NG, NI, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PS, PT, PW, PY, QA, RE, RO, RS, RU, RW, SA, SB, SC, SD, SE, SG, SH, SI, SJ, SK, SL, SM, SN, SO, SR, SS, ST, SV, SX, SY, SZ, TC, TD, TF, TG, TH, TJ, TK, TL, TM, TN, TO, TR, TT, TV, TW, TZ, UA, UG, UM, US, UY, UZ, VA, VC, VE, VG, VI, VN, VU, WF, WS, YE, YT, ZA, ZM, ZW; 5 | } 6 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/article/enumwitannotations/Country.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples.article.enumwitannotations; 2 | 3 | import org.enumus.initializer.Initializable; 4 | import org.enumus.initializer.IntValue; 5 | import org.enumus.initializer.Value; 6 | import org.enumus.samples.article.IsoAlpha2; 7 | 8 | public enum Country implements Initializable { 9 | @Value(name = "name", value = "French Republic") 10 | @Value(name = "president", value = "Emmanuel Macron") 11 | @Value(name = "primeMinister", value = "Édouard Philippe") 12 | @IntValue(name = "countryCode", value = 33) 13 | @IsoCountryCode(name = "iso", iso = IsoAlpha2.FR) 14 | FRANCE(), 15 | 16 | 17 | @Value(name = "name", value = "United States of America") 18 | @Value(name = "president", value = "Donald Trump") 19 | @IntValue(name = "countryCode", value = 1) 20 | @IsoCountryCode(name = "iso", iso = IsoAlpha2.US) 21 | USA(), 22 | 23 | @Value(name = "name", value = "England") 24 | @Value(name = "monarch", value = "Elizabeth II") 25 | @Value(name = "primeMinister", value = "Theresa May") 26 | @IntValue(name = "countryCode", value = 44) 27 | ENGLAND(), 28 | 29 | @Value(name = "name", value = "England") 30 | @Value(name = "monarch", value = "Elizabeth II") 31 | @Value(name = "primeMinister", value = "Theresa May") 32 | @IntValue(name = "countryCode", value = 44) 33 | WELSH(), 34 | 35 | @Value(name = "name", value = "England") 36 | @Value(name = "monarch", value = "Elizabeth II") 37 | @Value(name = "primeMinister", value = "Nicola Sturgeon") 38 | @IntValue(name = "countryCode", value = 44) 39 | SCOTLAND(), 40 | 41 | 42 | @Value(name = "name", value = "The United Kingdom of Great Britain and Northern Ireland") 43 | @Value(name = "monarch", value = "Elizabeth II") 44 | @Value(name = "primeMinister", value = "Theresa May") 45 | @IntValue(name = "countryCode", value = 44) 46 | @IsoCountryCode(name = "iso", iso = IsoAlpha2.GB) 47 | UNITED_KINDOM(ENGLAND, WELSH, SCOTLAND), 48 | ; 49 | 50 | private final String name; 51 | private final String monarch; 52 | private final String president; 53 | private final String primeMinister; 54 | private final Country[] federatedState; 55 | private final int countryCode; 56 | private final IsoAlpha2 iso; 57 | 58 | 59 | // fdfdf 60 | Country(Country ... countries) { 61 | this.name = $(); 62 | this.monarch = $(); 63 | this.president = $(); 64 | this.primeMinister = $(); 65 | this.federatedState = $(countries); 66 | this.countryCode = $(); 67 | this.iso = $(); 68 | } 69 | 70 | public String getName() { 71 | return name; 72 | } 73 | 74 | public String getMonarch() { 75 | return monarch; 76 | } 77 | 78 | public String getPresident() { 79 | return president; 80 | } 81 | 82 | public String getPrimeMinister() { 83 | return primeMinister; 84 | } 85 | 86 | public Country[] getFederatedState() { 87 | return federatedState; 88 | } 89 | 90 | public int getCountryCode() { 91 | return countryCode; 92 | } 93 | 94 | public IsoAlpha2 getIso() { 95 | return iso; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/article/enumwitannotations/IsoCountryCode.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples.article.enumwitannotations; 2 | 3 | 4 | import org.enumus.initializer.Argument; 5 | import org.enumus.initializer.Value; 6 | import org.enumus.samples.article.IsoAlpha2; 7 | 8 | import java.lang.annotation.ElementType; 9 | import java.lang.annotation.Retention; 10 | import java.lang.annotation.RetentionPolicy; 11 | import java.lang.annotation.Target; 12 | 13 | @Retention(RetentionPolicy.RUNTIME) 14 | @Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD}) 15 | @Value(name = "${name}", value = "${iso}", type = IsoAlpha2.class, factory = IsoAlpha2.class) 16 | @Argument 17 | public @interface IsoCountryCode { 18 | String name(); 19 | IsoAlpha2 iso(); 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/article/withenum/Country.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples.article.withenum; 2 | 3 | import org.enumus.samples.article.IsoAlpha2; 4 | 5 | import java.util.Arrays; 6 | import java.util.Collection; 7 | import java.util.Collections; 8 | 9 | public enum Country { 10 | FRANCE("French Republic", null, "Emmanuel Macron", "Édouard Philippe", Collections.emptyList(), 33, IsoAlpha2.FR), 11 | USA("The United states of America", null, "Donald Trump", null, Arrays.asList(/*too long...*/), 1, IsoAlpha2.US), 12 | 13 | ENGLAND("England", "Elizabeth II", null, "Theresa May", Collections.emptyList(), 44, IsoAlpha2.GB), 14 | WELSH("England", "Elizabeth II", null, "Theresa May", Collections.emptyList(), 44, IsoAlpha2.GB), 15 | SCOTLAND("England", "Elizabeth II", null, "Nicola Sturgeon", Collections.emptyList(), 44, IsoAlpha2.GB), 16 | UNITED_KINDOM("The United Kingdom of Great Britain and Northern Ireland", "Elizabeth II", null, "Theresa May", Arrays.asList(ENGLAND, WELSH, SCOTLAND), 44, IsoAlpha2.GB), 17 | ; 18 | 19 | private final String name; 20 | private final String monarch; 21 | private final String president; 22 | private final String primeMinister; 23 | private final Collection federatedState; 24 | private final int countryCode; 25 | private final IsoAlpha2 iso; 26 | 27 | 28 | 29 | Country(String name, String monarch, String president, String primeMinister, Collection federatedState, int countryCode, IsoAlpha2 iso) { 30 | this.name = name; 31 | this.monarch = monarch; 32 | this.president = president; 33 | this.primeMinister = primeMinister; 34 | this.federatedState = federatedState; 35 | this.countryCode = countryCode; 36 | this.iso = iso; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/org/enumus/samples/article/withoutenum/Country.java: -------------------------------------------------------------------------------- 1 | package org.enumus.samples.article.withoutenum; 2 | 3 | import org.enumus.samples.article.IsoAlpha2; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.Collection; 8 | import java.util.Collections; 9 | 10 | public class Country { 11 | private final String name; 12 | private final String monarch; 13 | private final String president; 14 | private final String primeMinister; 15 | private final Collection federatedState; 16 | private final int countryCode; 17 | private final IsoAlpha2 iso; 18 | 19 | 20 | public Country(String name, String monarch, String president, String primeMinister, Collection federatedState, int countryCode, IsoAlpha2 iso) { 21 | this.name = name; 22 | this.monarch = monarch; 23 | this.president = president; 24 | this.primeMinister = primeMinister; 25 | this.federatedState = federatedState; 26 | this.countryCode = countryCode; 27 | this.iso = iso; 28 | } 29 | 30 | public static CountryBuilder builder() { 31 | return new CountryBuilder(); 32 | } 33 | 34 | public static class CountryBuilder { 35 | private String name; 36 | private String monarch; 37 | private String president; 38 | private String primeMinister; 39 | private Collection federatedState = new ArrayList<>(); 40 | private int countryCode; 41 | private IsoAlpha2 iso; 42 | 43 | public CountryBuilder named(String name) { 44 | this.name = name; 45 | return this; 46 | } 47 | 48 | public CountryBuilder ruledBy(String monarch) { 49 | this.monarch = monarch; 50 | return this; 51 | } 52 | 53 | public CountryBuilder leadBy(String president) { 54 | this.president = president; 55 | return this; 56 | } 57 | 58 | public CountryBuilder govermentHeadedBy(String primeMinister) { 59 | this.primeMinister = primeMinister; 60 | return this; 61 | } 62 | 63 | public CountryBuilder withPhoneCode(int countryCode) { 64 | this.countryCode = countryCode; 65 | return this; 66 | } 67 | 68 | public CountryBuilder federates(Country part) { 69 | federatedState.add(part); 70 | return this; 71 | } 72 | 73 | public CountryBuilder withIso(IsoAlpha2 iso) { 74 | this.iso = iso; 75 | return this; 76 | } 77 | 78 | public Country build(){ 79 | return new Country(name, monarch, president,primeMinister, federatedState, countryCode, iso); 80 | } 81 | } 82 | 83 | 84 | public static void main(String[] args ) { 85 | 86 | } 87 | 88 | private static void callConstructor() { 89 | Country gb = new Country("The United Kingdom of Great Britain and Northern Ireland", "Elizabeth II", null, "Theresa May", 90 | Arrays.asList( 91 | new Country("England", "Elizabeth II", null, "Theresa May", null, 44, IsoAlpha2.GB), 92 | new Country("Welsh", "Elizabeth II", null, "Theresa May", null, 44, IsoAlpha2.GB), 93 | new Country("Scotland", "Elizabeth II", null, "Nicola Sturgeon", null, 44, IsoAlpha2.GB) 94 | ), 95 | 44, IsoAlpha2.GB 96 | ); 97 | Country usa = new Country("The United states of America", null, "Donald Trump", null, Arrays.asList(/*too long...*/), 1, IsoAlpha2.US); 98 | Country france = new Country("French Republic", null, "Emmanuel Macron", "Édouard Philippe", Collections.emptyList(), 33, IsoAlpha2.FR); 99 | } 100 | 101 | private static void callBuilder() { 102 | Country gb = Country.builder().named("The United Kingdom of Great Britain and Northern Ireland").ruledBy("Elizabeth II").govermentHeadedBy("Theresa May") 103 | .federates(Country.builder().named("England").ruledBy("Elizabeth II").govermentHeadedBy("Theresa May").withPhoneCode(44).build()) 104 | .federates(Country.builder().named("Welsh").ruledBy("Elizabeth II").govermentHeadedBy("Theresa May").withPhoneCode(44).build()) 105 | .federates(Country.builder().named("Scotland").ruledBy("Elizabeth II").govermentHeadedBy("Nicola Sturgeon").withPhoneCode(44).build()) 106 | .build(); 107 | 108 | Country usa = Country.builder().named("The United states of America").leadBy("Donald Trump").withPhoneCode(1).build(); 109 | Country france = Country.builder().named("The United states of America").govermentHeadedBy("Édouard Philippe").leadBy("Emmanuel Macron").withPhoneCode(33).build(); 110 | } 111 | } 112 | --------------------------------------------------------------------------------