├── .gitignore ├── NOTICE.txt ├── README.md ├── src ├── main │ └── java │ │ └── com │ │ └── github │ │ └── meanbeanlib │ │ └── mirror │ │ ├── SerializableLambdas.java │ │ ├── ClassUtils.java │ │ ├── Executables.java │ │ └── Utility.java └── test │ └── java │ └── com │ └── github │ └── meanbeanlib │ └── mirror │ └── ExecutablesTest.java ├── pom.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Eclipse 3 | ################# 4 | *.classpath 5 | *.project 6 | *.settings 7 | */target/** 8 | /target/ 9 | /bin/** 10 | 11 | ################# 12 | ## Java 13 | ################# 14 | # Compiled class file 15 | *.class 16 | 17 | # Log file 18 | *.log 19 | 20 | # BlueJ files 21 | *.ctxt 22 | 23 | # Mobile Tools for Java (J2ME) 24 | .mtj.tmp/ 25 | 26 | # Package Files # 27 | *.jar 28 | *.war 29 | *.nar 30 | *.ear 31 | *.zip 32 | *.tar.gz 33 | *.rar 34 | 35 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 36 | hs_err_pid* 37 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | This notice is provided with respect to safety-mirror. 2 | 3 | --- begin of LICENSE --- 4 | 5 | Copyright 2018-2019 the original author or authors. 6 | 7 | Licensed under the Apache License, Version 2.0 (the "License"); 8 | you may not use this file except in compliance with the License. 9 | You may obtain a copy of the License at 10 | 11 | https://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | 19 | --- end of LICENSE --- 20 | 21 | ------------------------------------------------------------------------------- 22 | 23 | This notice is provided with respect to BCEL. 24 | 25 | --- begin of LICENSE --- 26 | Apache Commons BCEL 27 | Copyright 2004-2020 The Apache Software Foundation 28 | 29 | This product includes software developed at 30 | The Apache Software Foundation (https://www.apache.org/). 31 | 32 | --- end of LICENSE --- 33 | 34 | ------------------------------------------------------------------------------- 35 | 36 | This notice is provided with respect to spring-framework. 37 | 38 | --- begin of LICENSE --- 39 | 40 | Copyright 2002-2017 the original author or authors. 41 | 42 | Licensed under the Apache License, Version 2.0 (the "License"); 43 | you may not use this file except in compliance with the License. 44 | You may obtain a copy of the License at 45 | 46 | https://www.apache.org/licenses/LICENSE-2.0 47 | 48 | Unless required by applicable law or agreed to in writing, software 49 | distributed under the License is distributed on an "AS IS" BASIS, 50 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 51 | See the License for the specific language governing permissions and 52 | limitations under the License. 53 | 54 | --- end of LICENSE --- 55 | 56 | ------------------------------------------------------------------------------- 57 | 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # meanmirror 2 | 3 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.github.meanbeanlib/meanmirror/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.meanbeanlib/meanmirror) 4 | ![Java CI](https://github.com/meanbeanlib/meanmirror/workflows/Java%20CI/badge.svg) 5 | 6 | ## Usage 7 | Simply pass a [method reference](https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html) to `Executables` 8 | class. This will provide you with a `java.lang.reflect.Method` or a `java.lang.reflect.Constructor`. 9 | 10 | // Get method 11 | Method containsMethod = Executables.findMethod(String::contains); 12 | 13 | // Get another method 14 | Method getPropertyMethod = Executables.findMethod(MyBean::getProperty); 15 | 16 | // Get method that throws checked exception 17 | Method exceptionThrowingMethod = Executables.findMethod(Files::deleteIfExists); 18 | 19 | // To get vararg method, you must specify parameters in generics 20 | Method varargMethod = Executables.[]> findMethod(Files::createDirectories); 21 | 22 | // Get constructor 23 | Constructor ctor = Executables.findConstructor(MyBean::new); 24 | 25 | Notice that you have to provide the method parameters in generics under certain circumstances (When the method is overloaded, or if the method has a varargs parameter). 26 | 27 | The project requires Java 8 or above. 28 | 29 | ## Dependency Management 30 | 31 | Add this to your pom.xml: 32 | 33 | ``` 34 | 35 | com.github.meanbeanlib 36 | meanmirror 37 | 1.0.0 38 | 39 | ``` 40 | 41 | ## History 42 | 43 | This is a fork of [safety-mirror](https://github.com/Hervian/safety-mirror/) project. 44 | 45 | ## License 46 | 47 | This code is released under the Apache 2.0 license. 48 | ​​​​​​ 49 | 50 | meanmirror 51 | 52 | Copyright (C) 2020 the original author or authors. 53 | 54 | Licensed under the Apache License, Version 2.0 (the "License"); 55 | you may not use this file except in compliance with the License. 56 | You may obtain a copy of the License at 57 | 58 | http://www.apache.org/licenses/LICENSE-2.0 59 | 60 | Unless required by applicable law or agreed to in writing, software 61 | distributed under the License is distributed on an "AS IS" BASIS, 62 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 63 | See the License for the specific language governing permissions and 64 | limitations under the License. 65 | 66 | 67 | -------------------------------------------------------------------------------- /src/main/java/com/github/meanbeanlib/mirror/SerializableLambdas.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * ​​​ 3 | * meanmirror 4 | * ⁣⁣⁣ 5 | * Copyright (C) 2020 the original author or authors. 6 | * ⁣⁣⁣ 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | *  19 | */ 20 | 21 | package com.github.meanbeanlib.mirror; 22 | 23 | import java.io.Serializable; 24 | 25 | public class SerializableLambdas { 26 | 27 | public static interface SerializableLambda extends Serializable { 28 | } 29 | 30 | @FunctionalInterface 31 | public static interface SerializableConsumer0 extends SerializableLambda { 32 | void exec() throws Throwable; 33 | } 34 | 35 | @FunctionalInterface 36 | public static interface SerializableConsumer1 extends SerializableLambda { 37 | void exec(T1 t1) throws Throwable; 38 | } 39 | 40 | @FunctionalInterface 41 | public static interface SerializableConsumer2 extends SerializableLambda { 42 | void exec(T1 t1, T2 t2) throws Throwable; 43 | } 44 | 45 | @FunctionalInterface 46 | public static interface SerializableConsumer3 extends SerializableLambda { 47 | void exec(T1 t1, T2 t2, T3 t3) throws Throwable; 48 | } 49 | 50 | @FunctionalInterface 51 | public static interface SerializableConsumer4 extends SerializableLambda { 52 | void exec(T1 t1, T2 t2, T3 t3, T4 t4) throws Throwable; 53 | } 54 | 55 | @FunctionalInterface 56 | public static interface SerializableFunction0 extends SerializableLambda { 57 | R exec() throws Throwable; 58 | } 59 | 60 | @FunctionalInterface 61 | public static interface SerializableFunction1 extends SerializableLambda { 62 | R exec(T1 t1) throws Throwable; 63 | } 64 | 65 | @FunctionalInterface 66 | public static interface SerializableFunction2 extends SerializableLambda { 67 | R exec(T1 t1, T2 t2) throws Throwable; 68 | } 69 | 70 | @FunctionalInterface 71 | public static interface SerializableFunction3 extends SerializableLambda { 72 | R exec(T1 t1, T2 t2, T3 t3) throws Throwable; 73 | } 74 | 75 | @FunctionalInterface 76 | public static interface SerializableFunction4 extends SerializableLambda { 77 | R exec(T1 t1, T2 t2, T3 t3, T3 t4) throws Throwable; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | 4 | com.github.meanbeanlib 5 | meanmirror 6 | 1.1.0-SNAPSHOT 7 | jar 8 | meanmirror 9 | 10 | meanmirror provides reflection utilities. 11 | 12 | http://github.com/meanbeanlib/meanmirror/ 13 | 2020 14 | 15 | meanbean 16 | 17 | 18 | 19 | UTF-8 20 | 8 21 | 8 22 | 23 | 24 | 25 | 26 | Apache 2 27 | http://www.apache.org/licenses/LICENSE-2.0.txt 28 | manual 29 | A business-friendly OSS license 30 | 31 | 32 | 33 | 34 | scm:git:git://github.com/meanbeanlib/meanmirror.git 35 | scm:git:https://github.com/meanbeanlib/meanmirror.git 36 | http://github.com/meanbeanlib/meanmirror/tree/master 37 | HEAD 38 | 39 | 40 | 41 | 42 | meanbean 43 | meanbean 44 | 60596288+meanbeanlib@users.noreply.github.com 45 | 46 | developer 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | org.apache.maven.plugins 55 | maven-compiler-plugin 56 | 3.8.1 57 | 58 | 1.8 59 | 1.8 60 | true 61 | true 62 | 63 | 64 | 65 | org.apache.maven.plugins 66 | maven-source-plugin 67 | 3.2.0 68 | 69 | 70 | attach-sources 71 | 72 | jar 73 | 74 | 75 | 76 | 77 | 78 | org.apache.maven.plugins 79 | maven-jar-plugin 80 | 3.2.0 81 | 82 | 83 | 84 | test-jar 85 | 86 | 87 | 88 | 89 | 90 | org.apache.maven.plugins 91 | maven-javadoc-plugin 92 | 3.1.1 93 | 94 | 95 | 96 | jar 97 | 98 | 99 | 100 | 101 | 102 | org.codehaus.mojo 103 | license-maven-plugin 104 | 2.0.0 105 | 106 | false 107 | the original author or authors. 108 | true 109 | apache_v2 110 | ​​​ 111 |  112 | ⁣⁣⁣ 113 | 114 | 115 | 116 | license 117 | 118 | update-file-header 119 | 120 | process-sources 121 | 122 | apache_v2 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | maven-release-plugin 132 | 3.0.0-M1 133 | 134 | 135 | 136 | 137 | 138 | 139 | junit 140 | junit 141 | 4.13 142 | test 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /src/test/java/com/github/meanbeanlib/mirror/ExecutablesTest.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * ​​​ 3 | * meanmirror 4 | * ⁣⁣⁣ 5 | * Copyright (C) 2010 - 2020 the original author or authors. 6 | * ⁣⁣⁣ 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | *  19 | */ 20 | 21 | package com.github.meanbeanlib.mirror; 22 | 23 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableConsumer1; 24 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableConsumer2; 25 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableConsumer3; 26 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableFunction1; 27 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableFunction2; 28 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableFunction3; 29 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableFunction4; 30 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableLambda; 31 | import org.junit.Test; 32 | 33 | import java.io.BufferedReader; 34 | import java.lang.reflect.Constructor; 35 | import java.util.HashMap; 36 | 37 | import static org.junit.Assert.assertEquals; 38 | import static org.junit.Assert.assertNotNull; 39 | 40 | public class ExecutablesTest { 41 | 42 | @Test 43 | public void testFindMethod() { 44 | // final class 45 | assertNotNull(Executables.findMethod(String::isEmpty)); 46 | 47 | //throws checked exception 48 | assertNotNull(Executables.findMethod(BufferedReader::readLine)); 49 | 50 | // final method 51 | assertNotNull(Executables.findMethod(Thread::isAlive)); 52 | 53 | // to get vararg method you must specify parameters in generics 54 | assertNotNull(Executables.[]> findMethod(getClass()::getDeclaredMethod)); 55 | assertNotNull(Executables.findMethod((SerializableConsumer2[]>) getClass()::getDeclaredMethod)); 56 | 57 | // Class.forName is overloaded. 58 | // to get overloaded method you must specify parameters in generics 59 | assertNotNull(Executables. findMethod(Class::forName)); 60 | assertNotNull(Executables.findMethod((SerializableConsumer1) Class::forName)); 61 | assertNotNull(Executables. findMethodName(Class::forName)); 62 | assertNotNull(Executables.findMethod((SerializableConsumer3) Class::forName)); 63 | 64 | // Works with inherited methods 65 | assertNotNull(Executables.findMethod(this::toString)); 66 | 67 | assertNotNull(Executables. findMethod(this::newThread)); 68 | 69 | assertNotNull(Executables.findMethod(ExecutablesTest::testFindMethod)); 70 | assertNotNull(Executables.findMethod(new ExecutablesTest()::testFindMethod)); 71 | 72 | assertNotNull(Executables.findMethod(new HashMap<>()::entrySet)); 73 | assertNotNull(Executables.findMethod(getClass()::getDeclaredMethods)); 74 | 75 | assertNotNull(Executables.findExecutable((MySerializableLambda) new MyClass()::manyParams)); 76 | } 77 | 78 | @Test 79 | public void testConstructor() { 80 | verifyConstructor(0, Executables.findConstructor(ExecutablesTest::new)); 81 | verifyConstructor(0, Executables.findConstructor0(ExecutablesTest::new)); 82 | 83 | verifyConstructor(1, Executables.findConstructor1((SerializableFunction1) Thread::new)); 84 | verifyConstructor(1, Executables. findConstructor1(Thread::new)); 85 | 86 | verifyConstructor(2, Executables.findConstructor((SerializableFunction2) Thread::new)); 87 | verifyConstructor(2, Executables. findConstructor2(Thread::new)); 88 | 89 | verifyConstructor(3, 90 | Executables.findConstructor((SerializableFunction3) Thread::new)); 91 | verifyConstructor(3, Executables. findConstructor3(Thread::new)); 92 | 93 | verifyConstructor(4, Executables.findConstructor( 94 | (SerializableFunction4) MyConstructorClass::new)); 95 | verifyConstructor(4, Executables 96 | . findConstructor4(MyConstructorClass::new)); 97 | 98 | verifyConstructor(4, Executables.findConstructor(MyConstructorClass::new)); 99 | } 100 | 101 | @Test 102 | public void testGetName() throws Throwable { 103 | assertEquals("concat", Executables.findMethodName(String::concat)); 104 | assertEquals("isEmpty", Executables.findMethodName(String::isEmpty)); 105 | assertEquals("readLine", Executables.findMethodName(BufferedReader::readLine)); 106 | assertEquals("isAlive", Executables.findMethodName(Thread::isAlive)); 107 | assertEquals("getDeclaredField", Executables.findMethodName(getClass()::getDeclaredField)); 108 | assertEquals("forName", Executables. findMethodName(Class::forName)); 109 | assertEquals("forName", Executables. findMethodName(Class::forName)); 110 | assertEquals("toString", Executables.findMethodName(this::toString)); 111 | assertEquals("testFindMethod", Executables.findMethodName(ExecutablesTest::testFindMethod)); 112 | assertEquals("testFindMethod", Executables.findMethodName(new ExecutablesTest()::testFindMethod)); 113 | assertEquals("manyParams", Executables.findName((MySerializableLambda) new MyClass()::manyParams)); 114 | } 115 | 116 | @Test(expected = IllegalArgumentException.class) 117 | public void testIllegal() { 118 | Executables.findName(new MyImpropertlyAppliedClass()); 119 | } 120 | 121 | private void verifyConstructor(int paramCount, Constructor constructor) { 122 | assertEquals(paramCount, constructor.getParameterCount()); 123 | } 124 | 125 | private Thread newThread(ThreadGroup group, String[] name, long stackSize, int[] others) { 126 | return null; 127 | } 128 | 129 | private static interface MySerializableLambda extends SerializableLambda { 130 | public String manyParamsMethod(String a1, String a2, String a3, String a4, String a5, String a6, String a7); 131 | } 132 | 133 | public static class MyClass { 134 | 135 | public String manyParams(String a1, String a2, String a3, String a4, String a5, String a6, String a7) { 136 | return "hello world"; 137 | } 138 | } 139 | 140 | public static class MyImpropertlyAppliedClass implements SerializableLambda { 141 | 142 | private static final long serialVersionUID = 5829601569699926661L; 143 | 144 | public String manyParams(String a1, String a2, String a3, String a4, String a5, String a6, String a7) { 145 | return "hello world"; 146 | } 147 | } 148 | 149 | public static class MyConstructorClass implements SerializableLambda { 150 | 151 | public MyConstructorClass(ThreadGroup arg1, Runnable arg2, String arg3, String arg4) { 152 | 153 | } 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/main/java/com/github/meanbeanlib/mirror/ClassUtils.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * ​​​ 3 | * meanmirror 4 | * ⁣⁣⁣ 5 | * Copyright (C) 2020 the original author or authors. 6 | * ⁣⁣⁣ 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | *  19 | */ 20 | 21 | /* 22 | * spring-framework 23 | * 24 | * Copyright 2002-2020 the original author or authors. 25 | * 26 | * Licensed under the Apache License, Version 2.0 (the "License"); 27 | * you may not use this file except in compliance with the License. 28 | * You may obtain a copy of the License at 29 | * 30 | * https://www.apache.org/licenses/LICENSE-2.0 31 | * 32 | * Unless required by applicable law or agreed to in writing, software 33 | * distributed under the License is distributed on an "AS IS" BASIS, 34 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 35 | * See the License for the specific language governing permissions and 36 | * limitations under the License. 37 | */ 38 | 39 | package com.github.meanbeanlib.mirror; 40 | 41 | import java.io.Closeable; 42 | import java.io.Externalizable; 43 | import java.io.Serializable; 44 | import java.lang.reflect.Array; 45 | import java.util.Collection; 46 | import java.util.Collections; 47 | import java.util.Enumeration; 48 | import java.util.HashMap; 49 | import java.util.HashSet; 50 | import java.util.IdentityHashMap; 51 | import java.util.Iterator; 52 | import java.util.List; 53 | import java.util.Map; 54 | import java.util.Objects; 55 | import java.util.Optional; 56 | import java.util.Set; 57 | 58 | class ClassUtils { 59 | 60 | /** Suffix for array class names: {@code "[]"}. */ 61 | private static final String ARRAY_SUFFIX = "[]"; 62 | 63 | /** Prefix for internal array class names: {@code "["}. */ 64 | private static final String INTERNAL_ARRAY_PREFIX = "["; 65 | 66 | /** Prefix for internal non-primitive array class names: {@code "[L"}. */ 67 | private static final String NON_PRIMITIVE_ARRAY_PREFIX = "[L"; 68 | 69 | /** The package separator character: {@code '.'}. */ 70 | private static final char PACKAGE_SEPARATOR = '.'; 71 | 72 | /** The inner class separator character: {@code '$'}. */ 73 | private static final char INNER_CLASS_SEPARATOR = '$'; 74 | 75 | /** 76 | * Map with primitive wrapper type as key and corresponding primitive 77 | * type as value, for example: Integer.class -> int.class. 78 | */ 79 | private static final Map, Class> primitiveWrapperTypeMap = new IdentityHashMap<>(8); 80 | 81 | /** 82 | * Map with primitive type name as key and corresponding primitive 83 | * type as value, for example: "int" -> "int.class". 84 | */ 85 | private static final Map> primitiveTypeNameMap = new HashMap<>(32); 86 | 87 | /** 88 | * Map with common Java language class name as key and corresponding Class as value. 89 | * Primarily for efficient deserialization of remote invocations. 90 | */ 91 | private static final Map> commonClassCache = new HashMap<>(64); 92 | 93 | static { 94 | primitiveWrapperTypeMap.put(Boolean.class, boolean.class); 95 | primitiveWrapperTypeMap.put(Byte.class, byte.class); 96 | primitiveWrapperTypeMap.put(Character.class, char.class); 97 | primitiveWrapperTypeMap.put(Double.class, double.class); 98 | primitiveWrapperTypeMap.put(Float.class, float.class); 99 | primitiveWrapperTypeMap.put(Integer.class, int.class); 100 | primitiveWrapperTypeMap.put(Long.class, long.class); 101 | primitiveWrapperTypeMap.put(Short.class, short.class); 102 | primitiveWrapperTypeMap.put(Void.class, void.class); 103 | 104 | // Map entry iteration is less expensive to initialize than forEach with lambdas 105 | for (Map.Entry, Class> entry : primitiveWrapperTypeMap.entrySet()) { 106 | registerCommonClasses(entry.getKey()); 107 | } 108 | 109 | Set> primitiveTypes = new HashSet<>(32); 110 | primitiveTypes.addAll(primitiveWrapperTypeMap.values()); 111 | Collections.addAll(primitiveTypes, boolean[].class, byte[].class, char[].class, 112 | double[].class, float[].class, int[].class, long[].class, short[].class); 113 | primitiveTypes.add(void.class); 114 | for (Class primitiveType : primitiveTypes) { 115 | primitiveTypeNameMap.put(primitiveType.getName(), primitiveType); 116 | } 117 | 118 | registerCommonClasses(Boolean[].class, Byte[].class, Character[].class, Double[].class, 119 | Float[].class, Integer[].class, Long[].class, Short[].class); 120 | registerCommonClasses(Number.class, Number[].class, String.class, String[].class, 121 | Class.class, Class[].class, Object.class, Object[].class); 122 | registerCommonClasses(Throwable.class, Exception.class, RuntimeException.class, 123 | Error.class, StackTraceElement.class, StackTraceElement[].class); 124 | registerCommonClasses(Enum.class, Iterable.class, Iterator.class, Enumeration.class, 125 | Collection.class, List.class, Set.class, Map.class, Map.Entry.class, Optional.class); 126 | 127 | Class[] javaLanguageInterfaceArray = { Serializable.class, Externalizable.class, 128 | Closeable.class, AutoCloseable.class, Cloneable.class, Comparable.class }; 129 | registerCommonClasses(javaLanguageInterfaceArray); 130 | } 131 | 132 | /** 133 | * Register the given common classes with the ClassUtils cache. 134 | */ 135 | private static void registerCommonClasses(Class... commonClasses) { 136 | for (Class clazz : commonClasses) { 137 | commonClassCache.put(clazz.getName(), clazz); 138 | } 139 | } 140 | 141 | public static Class resolvePrimitiveClassName(String name) { 142 | Class result = null; 143 | // Most class names will be quite long, considering that they 144 | // SHOULD sit in a package, so a length check is worthwhile. 145 | if (name != null && name.length() <= 7) { 146 | // Could be a primitive - likely. 147 | result = primitiveTypeNameMap.get(name); 148 | } 149 | return result; 150 | } 151 | 152 | public static Class forName(String name, ClassLoader classLoader) throws ClassNotFoundException { 153 | 154 | Objects.requireNonNull(name, "Name must not be null"); 155 | 156 | Class clazz = resolvePrimitiveClassName(name); 157 | if (clazz == null) { 158 | clazz = commonClassCache.get(name); 159 | } 160 | if (clazz != null) { 161 | return clazz; 162 | } 163 | 164 | // "java.lang.String[]" style arrays 165 | if (name.endsWith(ARRAY_SUFFIX)) { 166 | String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length()); 167 | Class elementClass = forName(elementClassName, classLoader); 168 | return Array.newInstance(elementClass, 0).getClass(); 169 | } 170 | 171 | // "[Ljava.lang.String;" style arrays 172 | if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) { 173 | String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1); 174 | Class elementClass = forName(elementName, classLoader); 175 | return Array.newInstance(elementClass, 0).getClass(); 176 | } 177 | 178 | // "[[I" or "[[Ljava.lang.String;" style arrays 179 | if (name.startsWith(INTERNAL_ARRAY_PREFIX)) { 180 | String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length()); 181 | Class elementClass = forName(elementName, classLoader); 182 | return Array.newInstance(elementClass, 0).getClass(); 183 | } 184 | 185 | ClassLoader clToUse = classLoader; 186 | if (clToUse == null) { 187 | clToUse = getDefaultClassLoader(); 188 | } 189 | try { 190 | return Class.forName(name, false, clToUse); 191 | } catch (ClassNotFoundException ex) { 192 | int lastDotIndex = name.lastIndexOf(PACKAGE_SEPARATOR); 193 | if (lastDotIndex != -1) { 194 | String innerClassName = name.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR 195 | + name.substring(lastDotIndex + 1); 196 | try { 197 | return Class.forName(innerClassName, false, clToUse); 198 | } catch (ClassNotFoundException ex2) { 199 | // Swallow - let original exception get through 200 | } 201 | } 202 | throw ex; 203 | } 204 | } 205 | 206 | public static ClassLoader getDefaultClassLoader() { 207 | ClassLoader cl = null; 208 | try { 209 | cl = Thread.currentThread().getContextClassLoader(); 210 | } catch (Throwable ex) { 211 | // Cannot access thread context ClassLoader - falling back... 212 | } 213 | if (cl == null) { 214 | // No thread context class loader -> use class loader of this class. 215 | cl = ClassUtils.class.getClassLoader(); 216 | if (cl == null) { 217 | // getClassLoader() returning null indicates the bootstrap ClassLoader 218 | try { 219 | cl = ClassLoader.getSystemClassLoader(); 220 | } catch (Throwable ex) { 221 | // Cannot access system ClassLoader - oh well, maybe the caller can live with null... 222 | } 223 | } 224 | } 225 | return cl; 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /src/main/java/com/github/meanbeanlib/mirror/Executables.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * ​​​ 3 | * meanmirror 4 | * ⁣⁣⁣ 5 | * Copyright (C) 2020 the original author or authors. 6 | * ⁣⁣⁣ 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | *  19 | */ 20 | 21 | package com.github.meanbeanlib.mirror; 22 | 23 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableConsumer0; 24 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableConsumer1; 25 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableConsumer2; 26 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableConsumer3; 27 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableConsumer4; 28 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableFunction0; 29 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableFunction1; 30 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableFunction2; 31 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableFunction3; 32 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableFunction4; 33 | import com.github.meanbeanlib.mirror.SerializableLambdas.SerializableLambda; 34 | 35 | import java.lang.invoke.SerializedLambda; 36 | import java.lang.reflect.Constructor; 37 | import java.lang.reflect.Executable; 38 | import java.lang.reflect.Method; 39 | import java.util.concurrent.Callable; 40 | 41 | /** 42 | * Find method or method name from a method reference.

43 | * 44 | *
 45 | 	// final class
 46 | 	assertNotNull(Executables.findMethod(String::isEmpty));
 47 | 	
 48 | 	//throws checked exception
 49 | 	assertNotNull(Executables.findMethod(BufferedReader::readLine));
 50 | 	
 51 | 	// final method
 52 | 	assertNotNull(Executables.findMethod(Thread::isAlive));
 53 | 	
 54 | 	// to get vararg method you must specify parameters in generics
 55 | 	assertNotNull(Executables.<String, Class<?>[]> findMethod(getClass()::getDeclaredMethod));
 56 | 	
 57 | 	// Class.forName is overloaded.
 58 | 	// to get overloaded method you must specify parameters in generics
 59 | 	assertNotNull(Executables.<String> findMethod(Class::forName));
 60 | 	
 61 | 	// Works with inherited methods
 62 | 	assertNotNull(Executables.findMethod(this::toString));
 63 | 	
 64 | 	assertNotNull(Executables.findMethod(MyBean::zeroArgsVoidReturningMethod));
 65 | 	assertNotNull(Executables.findMethod(new MyBean()::zeroArgsVoidReturningMethod));
 66 | 	
 67 | 	assertNotNull(Executables.findMethod(new HashMap<>()::entrySet));
 68 | 	assertNotNull(Executables.findMethod(getClass()::getDeclaredMethods));
 69 | 	
 70 | 	assertNotNull(Executables.findExecutable((MySerializableLambda) new MyClass()::manyParams));
 71 | 	
 72 | 	private static interface MySerializableLambda extends SerializableLambda {
 73 | 		public String methodWithManyParameters(String a1, String a2, String a3, String a4, String a5, String a6, String a7);
 74 | 	}
 75 | 	
 76 | 	public static class MyClass {
 77 | 	
 78 | 		public String manyParams(String a1, String a2, String a3, String a4, String a5, String a6, String a7) {
 79 | 			return "hello world";
 80 | 		}
 81 | 	}
 82 | 	
83 | */ 84 | public class Executables { 85 | 86 | public static Executable findExecutable(SerializableLambda consumer) { 87 | return doFindMethod(consumer); 88 | } 89 | 90 | public static Method findMethod(SerializableConsumer0 consumer) { 91 | return doFindMethod(consumer); 92 | } 93 | 94 | public static Method findGetter(SerializableFunction0 fn) { 95 | return doFindMethod(fn); 96 | } 97 | 98 | public static Method findMethod(SerializableConsumer1 consumer) { 99 | return (Method) doFindMethod(consumer); 100 | } 101 | 102 | public static Method findGetter(SerializableFunction1 fn) { 103 | return doFindMethod(fn); 104 | } 105 | 106 | public static Method findMethod(SerializableConsumer2 consumer) { 107 | return doFindMethod(consumer); 108 | } 109 | 110 | public static Method findGetter(SerializableFunction2 fn) { 111 | return doFindMethod(fn); 112 | } 113 | 114 | public static Method findMethod(SerializableConsumer3 consumer) { 115 | return doFindMethod(consumer); 116 | } 117 | 118 | public static Method findGetter(SerializableFunction3 fn) { 119 | return doFindMethod(fn); 120 | } 121 | 122 | public static Method findMethod(SerializableConsumer4 consumer) { 123 | return doFindMethod(consumer); 124 | } 125 | 126 | public static Method findGetter(SerializableFunction4 fn) { 127 | return doFindMethod(fn); 128 | } 129 | 130 | public static Constructor findConstructor(SerializableFunction0 fn) { 131 | return doFindMethod(fn); 132 | } 133 | 134 | public static Constructor findConstructor0(SerializableFunction0 fn) { 135 | return doFindMethod(fn); 136 | } 137 | 138 | public static Constructor findConstructor1(SerializableFunction1 fn) { 139 | return doFindMethod(fn); 140 | } 141 | 142 | public static Constructor findConstructor(SerializableFunction2 fn) { 143 | return doFindMethod(fn); 144 | } 145 | 146 | public static Constructor findConstructor2(SerializableFunction2 fn) { 147 | return doFindMethod(fn); 148 | } 149 | 150 | public static Constructor findConstructor(SerializableFunction3 fn) { 151 | return doFindMethod(fn); 152 | } 153 | 154 | public static Constructor findConstructor3(SerializableFunction3 fn) { 155 | return doFindMethod(fn); 156 | } 157 | 158 | public static Constructor findConstructor(SerializableFunction4 fn) { 159 | return doFindMethod(fn); 160 | } 161 | 162 | public static Constructor findConstructor4(SerializableFunction4 fn) { 163 | return doFindMethod(fn); 164 | } 165 | 166 | public static String findName(SerializableLambda consumer) { 167 | return doFindMethodName(consumer); 168 | } 169 | 170 | public static String findMethodName(SerializableConsumer0 consumer) { 171 | return doFindMethodName(consumer); 172 | } 173 | 174 | public static String findMethodName(SerializableConsumer1 consumer) { 175 | return doFindMethodName(consumer); 176 | } 177 | 178 | public static String findMethodName(SerializableConsumer2 consumer) { 179 | return doFindMethodName(consumer); 180 | } 181 | 182 | public static String findMethodName(SerializableConsumer3 consumer) { 183 | return doFindMethodName(consumer); 184 | } 185 | 186 | public static String findMethodName(SerializableConsumer4 consumer) { 187 | return doFindMethodName(consumer); 188 | } 189 | 190 | /** 191 | * Thanks to Holger for this StackOverflow answer: https://stackoverflow.com/a/21879031/6095334 192 | */ 193 | @SuppressWarnings("unchecked") 194 | private static E doFindMethod(SerializableLambda lambda) { 195 | Executable executable = runFinder(lambda, () -> { 196 | SerializedLambda serializedLambda = getSerializedLambda(lambda); 197 | 198 | String className = Utility.compactClassName(serializedLambda.getImplClass(), false); 199 | Class clazz = Class.forName(className); 200 | Class[] parameters = getParameters(serializedLambda.getImplMethodSignature()); 201 | String implMethodName = serializedLambda.getImplMethodName(); 202 | return "".equals(implMethodName) 203 | ? clazz.getDeclaredConstructor(parameters) 204 | : clazz.getDeclaredMethod(implMethodName, parameters); 205 | }); 206 | 207 | return (E) executable; 208 | } 209 | 210 | private static SerializedLambda getSerializedLambda(SerializableLambda lambda) throws ReflectiveOperationException { 211 | SerializedLambda serializedLambda = null; 212 | for (Class cl = lambda.getClass(); cl != null; cl = cl.getSuperclass()) { 213 | try { 214 | Method method = cl.getDeclaredMethod("writeReplace"); 215 | method.setAccessible(true); 216 | Object replacement = method.invoke(lambda); 217 | if (!(replacement instanceof SerializedLambda)) { 218 | break;// custom interface implementation 219 | } 220 | serializedLambda = (SerializedLambda) replacement; 221 | break; 222 | } catch (NoSuchMethodException e) { 223 | // ignore 224 | } 225 | } 226 | if (serializedLambda == null) { 227 | throw new IllegalArgumentException("Cannot find SerializedLambda for " + lambda 228 | + " . Is it a lambda method reference or an object?"); 229 | } 230 | return serializedLambda; 231 | } 232 | 233 | private static T runFinder(SerializableLambda lambda, Callable finder) { 234 | try { 235 | return finder.call(); 236 | } catch (IllegalArgumentException e) { 237 | throw e; 238 | 239 | } catch (Exception e) { 240 | throw new IllegalArgumentException("cannot find method for " + lambda, e); 241 | } 242 | } 243 | 244 | private static String doFindMethodName(SerializableLambda lambda) { 245 | return runFinder(lambda, () -> { 246 | SerializedLambda serializedLambda = getSerializedLambda(lambda); 247 | return serializedLambda.getImplMethodName(); 248 | }); 249 | } 250 | 251 | private static Class[] getParameters(String signature) throws ClassNotFoundException { 252 | String[] params = Utility.methodSignatureArgumentTypes(signature, false); 253 | 254 | Class[] paramTypes = new Class[params.length]; 255 | for (int i = 0; i < params.length; i++) { 256 | String className = params[i]; 257 | Class clazz = ClassUtils.forName(className, null); 258 | paramTypes[i] = clazz; 259 | } 260 | return paramTypes; 261 | } 262 | 263 | private Executables() { 264 | 265 | } 266 | } 267 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/main/java/com/github/meanbeanlib/mirror/Utility.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * ​​​ 3 | * meanmirror 4 | * ⁣⁣⁣ 5 | * Copyright (C) 2020 the original author or authors. 6 | * ⁣⁣⁣ 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | *  19 | */ 20 | 21 | package com.github.meanbeanlib.mirror; 22 | 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | 26 | /** 27 | * Utility functions that do not really belong to any class in particular. 28 | * 29 | */ 30 | // @since 6.0 methods are no longer final 31 | abstract class Utility { 32 | 33 | private static int unwrap(final ThreadLocal tl) { 34 | return tl.get().intValue(); 35 | } 36 | 37 | private static void wrap(final ThreadLocal tl, final int value) { 38 | tl.set(Integer.valueOf(value)); 39 | } 40 | 41 | /* How many chars have been consumed 42 | * during parsing in typeSignatureToString(). 43 | * Read by methodSignatureToString(). 44 | * Set by side effect, but only internally. 45 | */ 46 | private static ThreadLocal consumed_chars = new ThreadLocal() { 47 | @Override 48 | protected Integer initialValue() { 49 | return Integer.valueOf(0); 50 | } 51 | }; 52 | 53 | /** 54 | * Shorten long class names, java/lang/String becomes 55 | * java.lang.String, 56 | * e.g.. If chopit is true the prefix java.lang 57 | * is also removed. 58 | * 59 | * @param str The long class name 60 | * @param chopit flag that determines whether chopping is executed or not 61 | * @return Compacted class name 62 | */ 63 | public static String compactClassName(final String str, final boolean chopit) { 64 | return compactClassName(str, "java.lang.", chopit); 65 | } 66 | 67 | /** 68 | * Shorten long class name str, i.e., chop off the prefix, 69 | * if the 70 | * class name starts with this string and the flag chopit is true. 71 | * Slashes / are converted to dots .. 72 | * 73 | * @param str The long class name 74 | * @param prefix The prefix the get rid off 75 | * @param chopit flag that determines whether chopping is executed or not 76 | * @return Compacted class name 77 | */ 78 | public static String compactClassName(String str, final String prefix, final boolean chopit) { 79 | final int len = prefix.length(); 80 | str = str.replace('/', '.'); // Is `/' on all systems, even DOS 81 | if (chopit) { 82 | // If string starts with `prefix' and contains no further dots 83 | if (str.startsWith(prefix) && (str.substring(len).indexOf('.') == -1)) { 84 | str = str.substring(len); 85 | } 86 | } 87 | return str; 88 | } 89 | 90 | /** 91 | * Converts argument list portion of method signature to string. 92 | * 93 | * @param signature Method signature 94 | * @param chopit flag that determines whether chopping is executed or not 95 | * @return String Array of argument types 96 | * @throws IllegalArgumentException 97 | */ 98 | public static String[] methodSignatureArgumentTypes(final String signature, final boolean chopit) 99 | throws IllegalArgumentException { 100 | final List vec = new ArrayList<>(); 101 | int index; 102 | try { 103 | // Skip any type arguments to read argument declarations between `(' and `)' 104 | index = signature.indexOf('(') + 1; 105 | if (index <= 0) { 106 | throw new IllegalArgumentException("Invalid method signature: " + signature); 107 | } 108 | while (signature.charAt(index) != ')') { 109 | vec.add(typeSignatureToString(signature.substring(index), chopit)); 110 | //corrected concurrent private static field acess 111 | index += unwrap(consumed_chars); // update position 112 | } 113 | } catch (final StringIndexOutOfBoundsException e) { // Should never occur 114 | throw new IllegalArgumentException("Invalid method signature: " + signature, e); 115 | } 116 | return vec.toArray(new String[vec.size()]); 117 | } 118 | 119 | /** 120 | * WARNING: 121 | * 122 | * There is some nomenclature confusion through much of the BCEL code base with 123 | * respect to the terms Descriptor and Signature. For the offical definitions see: 124 | * 125 | * @see 126 | * Descriptors in The Java Virtual Machine Specification 127 | * 128 | * @see 129 | * Signatures in The Java Virtual Machine Specification 130 | * 131 | * In brief, a descriptor is a string representing the type of a field or method. 132 | * Signatures are similar, but more complex. Signatures are used to encode declarations 133 | * written in the Java programming language that use types outside the type system of the 134 | * Java Virtual Machine. They are used to describe the type of any class, interface, 135 | * constructor, method or field whose declaration uses type variables or parameterized types. 136 | * 137 | * To parse a descriptor, call typeSignatureToString. 138 | * To parse a signature, call signatureToString. 139 | * 140 | * Note that if the signature string is a single, non-generic item, the call to 141 | * signatureToString reduces to a call to typeSignatureToString. 142 | * Also note, that if you only wish to parse the first item in a longer signature 143 | * string, you should call typeSignatureToString directly. 144 | */ 145 | 146 | /** 147 | * 148 | * This method converts a type signature string into a Java type declaration such as 149 | * `String[]' and throws a `ClassFormatException' when the parsed type is invalid. 150 | * 151 | * @param signature type signature 152 | * @param chopit flag that determines whether chopping is executed or not 153 | * @return string containing human readable type signature 154 | * @throws IllegalArgumentException 155 | * @since 6.4.0 156 | */ 157 | public static String typeSignatureToString(final String signature, final boolean chopit) throws IllegalArgumentException { 158 | //corrected concurrent private static field acess 159 | wrap(consumed_chars, 1); // This is the default, read just one char like `B' 160 | try { 161 | switch (signature.charAt(0)) { 162 | case 'B': 163 | return "byte"; 164 | case 'C': 165 | return "char"; 166 | case 'D': 167 | return "double"; 168 | case 'F': 169 | return "float"; 170 | case 'I': 171 | return "int"; 172 | case 'J': 173 | return "long"; 174 | case 'T': { // TypeVariableSignature 175 | final int index = signature.indexOf(';'); // Look for closing `;' 176 | if (index < 0) { 177 | throw new IllegalArgumentException("Invalid type variable signature: " + signature); 178 | } 179 | //corrected concurrent private static field acess 180 | wrap(consumed_chars, index + 1); // "Tblabla;" `T' and `;' are removed 181 | return compactClassName(signature.substring(1, index), chopit); 182 | } 183 | case 'L': { // Full class name 184 | // should this be a while loop? can there be more than 185 | // one generic clause? (markro) 186 | int fromIndex = signature.indexOf('<'); // generic type? 187 | if (fromIndex < 0) { 188 | fromIndex = 0; 189 | } else { 190 | fromIndex = signature.indexOf('>', fromIndex); 191 | if (fromIndex < 0) { 192 | throw new IllegalArgumentException("Invalid signature: " + signature); 193 | } 194 | } 195 | final int index = signature.indexOf(';', fromIndex); // Look for closing `;' 196 | if (index < 0) { 197 | throw new IllegalArgumentException("Invalid signature: " + signature); 198 | } 199 | 200 | // check to see if there are any TypeArguments 201 | final int bracketIndex = signature.substring(0, index).indexOf('<'); 202 | if (bracketIndex < 0) { 203 | // just a class identifier 204 | wrap(consumed_chars, index + 1); // "Lblabla;" `L' and `;' are removed 205 | return compactClassName(signature.substring(1, index), chopit); 206 | } 207 | // but make sure we are not looking past the end of the current item 208 | fromIndex = signature.indexOf(';'); 209 | if (fromIndex < 0) { 210 | throw new IllegalArgumentException("Invalid signature: " + signature); 211 | } 212 | if (fromIndex < bracketIndex) { 213 | // just a class identifier 214 | wrap(consumed_chars, fromIndex + 1); // "Lblabla;" `L' and `;' are removed 215 | return compactClassName(signature.substring(1, fromIndex), chopit); 216 | } 217 | 218 | // we have TypeArguments; build up partial result 219 | // as we recurse for each TypeArgument 220 | final StringBuilder type = new StringBuilder(compactClassName(signature.substring(1, bracketIndex), chopit)) 221 | .append("<"); 222 | int consumed_chars = bracketIndex + 1; // Shadows global var 223 | 224 | // check for wildcards 225 | if (signature.charAt(consumed_chars) == '+') { 226 | type.append("? extends "); 227 | consumed_chars++; 228 | } else if (signature.charAt(consumed_chars) == '-') { 229 | type.append("? super "); 230 | consumed_chars++; 231 | } 232 | 233 | // get the first TypeArgument 234 | if (signature.charAt(consumed_chars) == '*') { 235 | type.append("?"); 236 | consumed_chars++; 237 | } else { 238 | type.append(typeSignatureToString(signature.substring(consumed_chars), chopit)); 239 | // update our consumed count by the number of characters the for type argument 240 | consumed_chars = unwrap(Utility.consumed_chars) + consumed_chars; 241 | wrap(Utility.consumed_chars, consumed_chars); 242 | } 243 | 244 | // are there more TypeArguments? 245 | while (signature.charAt(consumed_chars) != '>') { 246 | type.append(", "); 247 | // check for wildcards 248 | if (signature.charAt(consumed_chars) == '+') { 249 | type.append("? extends "); 250 | consumed_chars++; 251 | } else if (signature.charAt(consumed_chars) == '-') { 252 | type.append("? super "); 253 | consumed_chars++; 254 | } 255 | if (signature.charAt(consumed_chars) == '*') { 256 | type.append("?"); 257 | consumed_chars++; 258 | } else { 259 | type.append(typeSignatureToString(signature.substring(consumed_chars), chopit)); 260 | // update our consumed count by the number of characters the for type argument 261 | consumed_chars = unwrap(Utility.consumed_chars) + consumed_chars; 262 | wrap(Utility.consumed_chars, consumed_chars); 263 | } 264 | } 265 | 266 | // process the closing ">" 267 | consumed_chars++; 268 | type.append(">"); 269 | 270 | if (signature.charAt(consumed_chars) == '.') { 271 | // we have a ClassTypeSignatureSuffix 272 | type.append("."); 273 | // convert SimpleClassTypeSignature to fake ClassTypeSignature 274 | // and then recurse to parse it 275 | type.append(typeSignatureToString("L" + signature.substring(consumed_chars + 1), chopit)); 276 | // update our consumed count by the number of characters the for type argument 277 | // note that this count includes the "L" we added, but that is ok 278 | // as it accounts for the "." we didn't consume 279 | consumed_chars = unwrap(Utility.consumed_chars) + consumed_chars; 280 | wrap(Utility.consumed_chars, consumed_chars); 281 | return type.toString(); 282 | } 283 | if (signature.charAt(consumed_chars) != ';') { 284 | throw new IllegalArgumentException("Invalid signature: " + signature); 285 | } 286 | wrap(Utility.consumed_chars, consumed_chars + 1); // remove final ";" 287 | return type.toString(); 288 | } 289 | case 'S': 290 | return "short"; 291 | case 'Z': 292 | return "boolean"; 293 | case '[': { // Array declaration 294 | int n; 295 | StringBuilder brackets; 296 | String type; 297 | int consumed_chars; // Shadows global var 298 | brackets = new StringBuilder(); // Accumulate []'s 299 | // Count opening brackets and look for optional size argument 300 | for (n = 0; signature.charAt(n) == '['; n++) { 301 | brackets.append("[]"); 302 | } 303 | consumed_chars = n; // Remember value 304 | // The rest of the string denotes a `' 305 | type = typeSignatureToString(signature.substring(n), chopit); 306 | //corrected concurrent private static field acess 307 | //Utility.consumed_chars += consumed_chars; is replaced by: 308 | final int _temp = unwrap(Utility.consumed_chars) + consumed_chars; 309 | wrap(Utility.consumed_chars, _temp); 310 | return type + brackets.toString(); 311 | } 312 | case 'V': 313 | return "void"; 314 | default: 315 | throw new IllegalArgumentException("Invalid signature: `" + signature + "'"); 316 | } 317 | } catch (final StringIndexOutOfBoundsException e) { // Should never occur 318 | throw new IllegalArgumentException("Invalid signature: " + signature, e); 319 | } 320 | } 321 | 322 | } 323 | --------------------------------------------------------------------------------