Patterns

Use Builder pattern to get instances of a class of type passed as a parameter

In order to accomplish the task, we will use a generic Builder class:

package com.yaroslavgrebnov.java.patterns.utils;

import java.lang.reflect.InvocationTargetException;

class Builder<T> {
  private final Class<T> classOfType;

  Builder(Class<T> classOfType) {
    this.classOfType = classOfType;
  }

  T getNewInstance() throws InvocationTargetException,
    InstantiationException,
    NoSuchMethodException,
    IllegalAccessException {
      return classOfType.getDeclaredConstructor().newInstance();
    }
}

The Builder class above can be used as follows:

SomeClass someClassInstance = new Builder<SomeClass>(SomeClass.class).getNewInstance();