Development docs
  • Introduction
  • General information
    • Development Ecosystem
    • Documentation
    • Testing
    • Continuous Integration
    • Code Style
    • Paradigms
    • Design Patterns
    • Architecture
    • Refactoring
    • Date Formats
  • Various
    • Technologies and services
      • Travis
      • GitHub
    • Databases
      • Database Kinds
      • Style Guide
      • Joins
    • Web
      • Template View
      • Interactive View
      • Open Graph
      • Twitter Card
    • Parsers
    • Regular Expression
    • File Formats
      • Properties
    • Logging
  • git
    • Configuration files
      • gitignore
      • gitattributes
    • Gitflow
    • Tools
  • Web
    • REST
    • SOAP
  • Architecture
    • SOA
  • Object Oriented Programming
    • Returns
  • Jenkins
    • Pipeline
      • Steps
      • Environment
      • Notifications
      • Scripts
  • Java
    • Environment
      • Development Ecosystem
      • IDE
    • General
    • Interfaces and Generics for a Service
      • Dependencies
      • Type Errors
      • Nested Type Errors
    • Creating New Instances Dynamically
      • Using Classes
      • Using Providers
Powered by GitBook
On this page

Was this helpful?

  1. Java
  2. Creating New Instances Dynamically

Using Classes

If you know the specific class you want, it can be used to generate a new instance:

public class ModelObjectBuilderWithClass<V extends ModelObject> implements ModelObjectBuilder<V> {

   private final Class<V> clz;

   public ModelObjectBuilderWithClass(final Class<V> clazz) {
      super();

      clz = clazz;
   }

   public V getModelObject(final String name) {
      final V obj;

      try {
         obj = clazz.newInstance();
      } catch (final InstantiationException | IllegalAccessException e) {
         throw new RuntimeException(e);
      }

      obj.setName(name);

      return obj;
   }

}
new ModelObjectBuilderWithClass(ModelObjectImpl.class);

Downsides

  • Handling exceptions

PreviousCreating New Instances DynamicallyNextUsing Providers

Last updated 6 years ago

Was this helpful?