ReflectionUtils.java

  1.  /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one
  3.  * or more contributor license agreements.  See the NOTICE file
  4.  * distributed with this work for additional information
  5.  * regarding copyright ownership.  The ASF licenses this file
  6.  * to you under the Apache License, Version 2.0 (the
  7.  * "License"); you may not use this file except in compliance
  8.  * with the License.  You may obtain a copy of the License at
  9.  *
  10.  *     http://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. package org.apache.commons.crypto.utils;

  19. import java.lang.ref.WeakReference;
  20. import java.lang.reflect.Constructor;
  21. import java.util.Arrays;
  22. import java.util.Collections;
  23. import java.util.Map;
  24. import java.util.WeakHashMap;

  25. import org.apache.commons.crypto.cipher.CryptoCipher;

  26. /**
  27.  * General utility methods for working with reflection.
  28.  */
  29. public final class ReflectionUtils {

  30.     /**
  31.      * A unique class which is used as a sentinel value in the caching for
  32.      * getClassByName. {@link #getClassByNameOrNull(String)}.
  33.      */
  34.     private static abstract class NegativeCacheSentinel {
  35.         // noop
  36.     }

  37.     private static final Map<ClassLoader, Map<String, WeakReference<Class<?>>>> CACHE_CLASSES = new WeakHashMap<>();

  38.     private static final ClassLoader CLASSLOADER;

  39.     static {
  40.         final ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
  41.         CLASSLOADER = threadClassLoader != null ? threadClassLoader : CryptoCipher.class.getClassLoader();
  42.     }

  43.     /**
  44.      * Sentinel value to store negative cache results in {@link #CACHE_CLASSES}.
  45.      */
  46.     private static final Class<?> NEGATIVE_CACHE_SENTINEL = NegativeCacheSentinel.class;

  47.     /**
  48.      * Loads a class by name.
  49.      *
  50.      * @param name the class name.
  51.      * @return the class object.
  52.      * @throws ClassNotFoundException if the class is not found.
  53.      */
  54.     public static Class<?> getClassByName(final String name) throws ClassNotFoundException {
  55.         final Class<?> ret = getClassByNameOrNull(name);
  56.         if (ret == null) {
  57.             throw new ClassNotFoundException("Class " + name + " not found");
  58.         }
  59.         return ret;
  60.     }

  61.     /**
  62.      * Loads a class by name, returning null rather than throwing an exception if it
  63.      * couldn't be loaded. This is to avoid the overhead of creating an exception.
  64.      *
  65.      * @param name the class name.
  66.      * @return the class object, or null if it could not be found.
  67.      */
  68.     private static Class<?> getClassByNameOrNull(final String name) {
  69.         final Map<String, WeakReference<Class<?>>> map;

  70.         synchronized (CACHE_CLASSES) {
  71.             map = CACHE_CLASSES.computeIfAbsent(CLASSLOADER, k -> Collections.synchronizedMap(new WeakHashMap<>()));
  72.         }

  73.         Class<?> clazz = null;
  74.         final WeakReference<Class<?>> ref = map.get(name);
  75.         if (ref != null) {
  76.             clazz = ref.get();
  77.         }

  78.         if (clazz == null) {
  79.             try {
  80.                 clazz = Class.forName(name, true, CLASSLOADER);
  81.             } catch (final ClassNotFoundException e) {
  82.                 // Leave a marker that the class isn't found
  83.                 map.put(name, new WeakReference<>(NEGATIVE_CACHE_SENTINEL));
  84.                 return null;
  85.             }
  86.             // two putters can race here, but they'll put the same class
  87.             map.put(name, new WeakReference<>(clazz));
  88.             return clazz;
  89.         }
  90.         if (clazz == NEGATIVE_CACHE_SENTINEL) {
  91.             return null; // not found
  92.         }
  93.         // cache hit
  94.         return clazz;
  95.     }

  96.     /**
  97.      * Uses the constructor represented by this {@code Constructor} object to create
  98.      * and initialize a new instance of the constructor's declaring class, with the
  99.      * specified initialization parameters.
  100.      *
  101.      * @param <T>   type for the new instance
  102.      * @param klass the Class object.
  103.      * @param args  array of objects to be passed as arguments to the constructor
  104.      *              call.
  105.      * @return a new object created by calling the constructor this object
  106.      *         represents.
  107.      */
  108.     public static <T> T newInstance(final Class<T> klass, final Object... args) {
  109.         try {
  110.             final Constructor<T> ctor;
  111.             final int argsLength = args.length;

  112.             if (argsLength == 0) {
  113.                 ctor = klass.getDeclaredConstructor();
  114.             } else {
  115.                 final Class<?>[] argClses = new Class[argsLength];
  116.                 Arrays.setAll(argClses, i -> args[i].getClass());
  117.                 ctor = klass.getDeclaredConstructor(argClses);
  118.             }
  119.             ctor.setAccessible(true);
  120.             return ctor.newInstance(args);
  121.         } catch (final Exception e) {
  122.             throw new IllegalArgumentException(e);
  123.         }
  124.     }

  125.     /**
  126.      * The private constructor of {@link ReflectionUtils}.
  127.      */
  128.     private ReflectionUtils() {
  129.     }
  130. }