All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jparams.object.builder.ObjectBuilder Maven / Gradle / Ivy

package com.jparams.object.builder;

import com.jparams.object.builder.path.Path;
import com.jparams.object.builder.type.Type;
import com.jparams.object.builder.type.TypeReference;
import com.jparams.object.builder.type.TypeResolver;

import static com.jparams.object.builder.util.Assertion.ifNotNull;

/**
 * ObjectBuilder can create an instance of any class using a combination of reflection and pre-defined value providers. This can be used to
 * generate dummy instances of objects. You can use ObjectBuilder as follows:
 *
 * 
 *  ObjectBuilder.withDefaultConfiguration().buildInstanceOf(MyClass.class);
 * 
*/ public class ObjectBuilder { private final ObjectFactory objectFactory; private ObjectBuilder(final ObjectFactory objectFactory) { this.objectFactory = objectFactory; } /** * Create an instance of the given class. * * @param clazz class * @param type * @return build */ public Build buildInstanceOf(final Class clazz) { final Type type = TypeResolver.resolve(ifNotNull(clazz)); final Path path = new Path("$", type, null); return objectFactory.create(path); } /** * Create an instance of the given type reference. Where this method differs from {@link ObjectBuilder#buildInstanceOf(Class)} is that this * supports creation of an object with generics. Example: * *
     *  ObjectBuilder.withDefaultConfiguration().buildInstanceOf(new TypeReference<List<String>>() {});
     * 
* * @param typeReference type reference * @param type * @return build */ public Build buildInstanceOf(final TypeReference typeReference) { return buildInstanceOf(ifNotNull(typeReference).getType()); } /** * Create an instance of the given type reference. Where this method differs from {@link ObjectBuilder#buildInstanceOf(Class)} is that this * supports creation of an object with generics. Example: * *
     *  ObjectBuilder.withDefaultConfiguration().buildInstanceOf(Type.forClass(List.class).withGenerics(String.class));
     * 
* * @param type type * @param type * @param return type * @return build */ public Build buildInstanceOf(final Type type) { final Path path = new Path("$", ifNotNull(type), null); return objectFactory.create(path); } /** * Create an instance of ObjectBuilder with default configuration. This is the same as calling: * *
     *  ObjectBuilder.withConfiguration(Configuration.defaultConfiguration());
     * 
* * @return builder */ public static ObjectBuilder withDefaultConfiguration() { return withConfiguration(Configuration.defaultConfiguration()); } /** * Create an instance of ObjectBuilder with the given configuration. * * @param configuration configuration * @return builder */ public static ObjectBuilder withConfiguration(final Configuration configuration) { return new ObjectBuilder(configuration.buildObjectFactory()); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy