Class MetaUtils

java.lang.Object
com.cedarsoftware.util.io.MetaUtils

public class MetaUtils extends Object
This utility class has the methods mostly related to reflection related code.
Author:
John DeRegnaucourt ([email protected])
Copyright (c) Cedar Software LLC

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

License

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*
  • Field Details

  • Method Details

    • setUseUnsafe

      public static void setUseUnsafe(boolean state)
      Globally turn on (or off) the 'unsafe' option of Class construction. The unsafe option is used when all constructors have been tried and the Java class could not be instantiated.
      Parameters:
      state - boolean true = on, false = off.
    • listOf

      @SafeVarargs public static <T> List<T> listOf(T... items)
      For JDK1.8 support. Remove this and change to List.of() for JDK11+
    • setOf

      @SafeVarargs public static <T> Set<T> setOf(T... items)
      For JDK1.8 support. Remove this and change to Set.of() for JDK11+
    • mapOf

      public static <K, V> Map<K,V> mapOf()
      For JDK1.8 support. Remove this and change to Map.of() for JDK11+
    • mapOf

      public static <K, V> Map<K,V> mapOf(K k, V v)
    • mapOf

      public static <K, V> Map<K,V> mapOf(K k1, V v1, K k2, V v2)
    • mapOf

      public static <K, V> Map<K,V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3)
    • getClassIfEnum

      public static Optional<Class<?>> getClassIfEnum(Class<?> c)
    • matchArgumentsToParameters

      public static List<Object> matchArgumentsToParameters(com.cedarsoftware.util.convert.Converter converter, Collection<Object> values, Parameter[] parameterTypes, boolean useNull)
      Build a List the same size of parameterTypes, where the objects in the list are ordered to best match the parameters. Values from the passed in list are used only once or never.
      Parameters:
      values - A list of potential arguments. This list can be smaller than parameterTypes or larger.
      parameterTypes - A list of classes that the values will be matched against.
      Returns:
      List of values that are best ordered to match the passed in parameter types. This list will be the same length as the passed in parameterTypes list.
    • indexOfSmallestValue

      public static int indexOfSmallestValue(int[] array)
      Returns the index of the smallest value in an array.
      Parameters:
      array - The array to search.
      Returns:
      The index of the smallest value, or -1 if the array is empty.
    • createCacheKey

      public static String createCacheKey(Class<?> c, Collection<?> args)
    • newInstance

      public static Object newInstance(com.cedarsoftware.util.convert.Converter converter, Class<?> c, Collection<?> argumentValues)
      Create a new instance of the passed in class c. You can optionally pass in argument values that will be best-matched to a constructor on c. You can pass in null or an empty list, in which case, other techniques will be used to attempt to instantiate the class. For security reasons, Process, ClassLoader, ProcessBuilder, Constructor, Method, and Field cannot be instantiated.
      Parameters:
      c - Class to instantiate.
      argumentValues - List of values to supply to a constructor on 'c'. The constructor chosen on 'c' will be the one with a combination of the most fields that are satisfied with non-null values from the 'argumentsValues.' The method will attempt to use values from the list as constructor arguments for the passed in class c, ordering them to best-fit the constructor, by matching the class type of the argument values to the class types of the parameters on 'c' constructors. It will use all constructors exhaustively, until it is successful. If not, then it will look at the 'unsafe' setting and attempt to use that.
      Returns:
      an instance of the passed in class.
      Throws:
      JsonIoException - if it could not instantiate the passed in class. In that case, it is best to create a ClassFactory for this specific class, and add that to the ReadOptions as an instantiator that is associated to the class 'c'. In the ClassFactory, the JsonObject containing the data from the associated JsonObject { } is passed in, allowing you to instantiate and load the values in one operation. If you do that, and no further sub-objects exist, or you load the sub-objects in your ClassFactory, make sure to return 'true' for isObjectFinal().
    • getLogMessage

      public static String getLogMessage(String methodName, Object[] args)
      Format a nice looking method signature for logging output
    • getLogMessage

      public static String getLogMessage(String methodName, Object[] args, int argCharLen)
    • getValueWithDefaultForNull

      public static <K, V> V getValueWithDefaultForNull(Map map, K key, V defaultValue)
    • getValueWithDefaultForMissing

      public static <K, V> V getValueWithDefaultForMissing(Map map, K key, V defaultValue)
    • setFieldValue

      public static void setFieldValue(Field field, Object instance, Object value)
    • trySetAccessible

      public static void trySetAccessible(AccessibleObject object)
    • safelyIgnoreException

      public static <T> T safelyIgnoreException(Callable<T> callable, T defaultValue)
    • safelyIgnoreException

      public static void safelyIgnoreException(Runnable runnable)
    • length

      public static int length(String s)
      Use this method when you don't want a length check to throw a NullPointerException when
      Parameters:
      s - string to return length of
      Returns:
      0 if string is null, otherwise the length of string.
    • trimLength

      public static int trimLength(String s)
      Returns the length of the trimmed string. If the length is null then it returns 0.
    • isPrimitive

      public static boolean isPrimitive(Class<?> c)
      Legacy API that many applications consumed.
    • isLogicalPrimitive

      public static boolean isLogicalPrimitive(Class<?> c)
      Legacy API that many applications consumed.
    • loadClassToSetOfStrings

      public static Map<Class<?>,Set<String>> loadClassToSetOfStrings(String fileName)
      Populates a map with a mapping of Class -> Set of Strings
    • commaSeparatedStringToSet

      public static Set<String> commaSeparatedStringToSet(String commaSeparatedString)
    • loadNonStandardMethodNames

      public static Map<Class<?>,Map<String,String>> loadNonStandardMethodNames(String fileName)
      Load custom writer classes based on contents of resources/customWriters.txt. Verify that classes listed are indeed valid classes loaded in the JVM.
      Returns:
      Map<Class < ?>, JsonWriter.JsonClassWriter> containing the resolved Class -> JsonClassWriter instance.
    • loadMapDefinition

      public static Map<String,String> loadMapDefinition(String resName)
      Load in a Map-style properties file. Expects key and value to be separated by a = (whitespace ignored). Ignores lines beginning with a # and it also ignores blank lines.
      Parameters:
      resName - String name of the resource file.
    • loadSetDefinition

      public static Set<String> loadSetDefinition(String resName)
      Load in a Set-style simple file of values. Expects values to be one per line. Ignores lines beginning with a # and it also ignores blank lines.
      Parameters:
      resName - String name of the resource file.
      Returns:
      the set of strings
    • loadResourceAsString

      public static String loadResourceAsString(String resourceName)
      Loads resource content as a String.
      Parameters:
      resourceName - Name of the resource file.
      Returns:
      Content of the resource file as a String.
    • loadResourceAsBytes

      public static byte[] loadResourceAsBytes(String resourceName)
      Loads resource content as a byte[].
      Parameters:
      resourceName - Name of the resource file.
      Returns:
      Content of the resource file as a byte[].
    • removeLeadingAndTrailingQuotes

      public static String removeLeadingAndTrailingQuotes(String input)
      Strip leading and trailing double quotes from the passed in String. If there are more than one set of quotes, ""this is weird"" then all leading and trailing quotes will be removed, yielding this is weird. Note that: ["""this is "really" weird""] will be: [this is "really" weird].
    • findClosest

      public static <T> T findClosest(Class<?> c, Map<Class<?>,T> workerClasses, T defaultClass)
      Fetch the closest class for the passed in Class. This method always fetches the closest class or returns the default class, doing the complicated inheritance distance checking. This method is only called when a cache miss has happened. A sentinel 'defaultClass' is returned when no class is found. This prevents future cache misses from re-attempting to find classes that do not have a custom writer.
      Parameters:
      c - Class of object for which fetch a custom writer
      workerClasses - The classes to search through
      defaultClass - the class to return when no viable class was found.
      Returns:
      JsonClassWriter for the custom class (if one exists), nullWriter otherwise.
    • loadNonRefs

      public static Set<Class<?>> loadNonRefs()
      Load the list of classes that are intended to be treated as non-referenceable, immutable classes.
      Returns:
      Set<Class < ?>> which is the loaded from resource/nonRefs.txt and verified to exist in JVM.