Class InstanceBuilder<T>

  • Type Parameters:
    T - type type of object returned by this instance builder

    public class InstanceBuilder<T>
    extends java.lang.Object
    Utility for creating objects dynamically.
    • Method Detail

      • ofType

        public static <T> InstanceBuilder<T> ofType​(java.lang.Class<T> type)
        Create an InstanceBuilder for the given type.

        The specified type is the type returned by build(), which is typically the common base type or interface of the instance being constructed.

      • ofType

        public static <T> InstanceBuilder<T> ofType​(TypeDescriptor<T> token)
        Create an InstanceBuilder for the given type.

        The specified type is the type returned by build(), which is typically the common base type or interface for the instance to be constructed.

        The TypeDescriptor argument allows specification of generic types. For example, a List<String> return type can be specified as ofType(new TypeDescriptor<List<String>>(){}).

      • fromClassName

        public InstanceBuilder<T> fromClassName​(java.lang.String name)
                                         throws java.lang.ClassNotFoundException
        Sets the class name to be constructed.

        If the name is a simple name (ie Class.getSimpleName()), then the package of the return type is added as a prefix.

        The default class is the return type, specified in ofType(java.lang.Class<T>).

        Modifies and returns the InstanceBuilder for chaining.

        Throws:
        java.lang.ClassNotFoundException - if no class can be found by the given name
      • fromClass

        public InstanceBuilder<T> fromClass​(java.lang.Class<?> factoryClass)
        Sets the factory class to use for instance construction.

        Modifies and returns the InstanceBuilder for chaining.

      • fromFactoryMethod

        public InstanceBuilder<T> fromFactoryMethod​(java.lang.String methodName)
        Sets the name of the factory method used to construct the instance.

        The default, if no factory method was specified, is to look for a class constructor.

        Modifies and returns the InstanceBuilder for chaining.

      • withArg

        public <ArgT> InstanceBuilder<T> withArg​(java.lang.Class<? super ArgT> argType,
                                                 ArgT value)
        Adds an argument to be passed to the factory method.

        The argument type is used to lookup the factory method. This type may be a supertype of the argument value's class.

        Modifies and returns the InstanceBuilder for chaining.

        Type Parameters:
        ArgT - the argument type
      • build

        public T build()
        Creates the instance by calling the factory method with the given arguments.

        Defaults

        Throws:
        java.lang.RuntimeException - if the method does not exist, on type mismatch, or if the method cannot be made accessible.