Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

findConstructor #1

Open
lpenaud opened this issue Apr 9, 2024 · 0 comments
Open

findConstructor #1

lpenaud opened this issue Apr 9, 2024 · 0 comments

Comments

@lpenaud
Copy link
Owner

lpenaud commented Apr 9, 2024

Add this code below to ReflectionUtils :

    /**
     * Get all public constructors of the given class.
     * @param <T> Class type.
     * @param type Target class
     * @return All public constructors.
     */
    @SuppressWarnings("unchecked")
    public static <T> Stream<Constructor<T>> getContructors(final Class<T> type) {
        return Arrays.stream((Constructor<T>[]) type.getConstructors());
    }

    /**
     * Find a constructor with the given parameter types.
     * @param <T> Type of the instance created by the constructor.
     * @param type Target type
     * @param args Parameter types.
     * @return A constructor or empty.
     */
    public static <T> Optional<Constructor<T>> findConstructor(final Class<T> type, final Class<?>... args) {
        return ReflectionUtils.getContructors(type)
                        .filter(args.length == 0 ? c -> c.getParameterCount() == 0
                                        : c -> ReflectionUtils.isAssignableEach(args, c.getParameterTypes()))
                        .findAny();
    }

    /**
     * Test if the array of type is assignale each other.
     * @param types1 Type to test.
     * @param types2 Target type.
     * @return True if the first array types are assignable to second ones.
     */
    public static boolean isAssignableEach(final Class<?>[] types1, final Class<?>[] types2) {
        if (types1.length != types2.length) {
            return false;
        }
        for (int i = 0; i < types1.length; i++) {
            if (!types1[i].isAssignableFrom(types2[i])) {
                return false;
            }
        }
        return true;
    }

Add a condition to verify primitive types ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant