Java initialize class by name

Create object/instance of class by name using Class.forName in java (examples)

2. Examples: create object/instance of class by name (Class.forName/java)

  1. We generally create of the instances of JDBC drivers by proving complete path of driver.
    • e.g. Class sqlDriver = Class.forName(“com.mysql.jdbc.Driver”);
  2. Let us look into the very simple example to create the instance of class ArrayList using class Class.
    1. Class loadClass = Class.forName(“java.util.ArrayList”);
    2. ArrayList arrayList = (ArrayList) loadClass.newInstance();
    3. arrayList.add(“Item 0”);
    4. arrayList.add(“Item 1”);
    1. We will create instance of Standard JDK class like ArrayList.
    2. We will create the instance thread in java using class Class.
    3. Create instance of User defined classes.
      1. We will create couple of custom classes.
      2. We will create their instance of custom classes using class Class.
      3. We will create objects USCitizen & SwissCitizen classes using newInstance() method.

      create class forname java example

      Fig 1: User defined objects

      3. Program: create object/instance of class by name (Class.forName/java)

      1. Citizen interface:

      • Citizen interface defines the couple of methods.
      • We will create couple of concrete class like USCitizen & SwissCitizen to implement Citizen interface.

      package org.learn; public interface Citizen

      2. USCitizen class:

      • USCitizen class implements Citizen interface.
      • Complete code of USCitizen class is as follows:
      package org.learn; import java.util.Random; import java.util.UUID; public class USCitizen implements Citizen < public void nationality() < System.out.println("I am US Citizen"); >public void identity() < Random random = new Random(); random.nextInt(); System.out.println("My identification number : "+random.nextInt()); >>

      3. SwissCitizen class:

      • SwissCitizen class implements Citizen interface.
      • Complete code of SwissCitizen class is as follows:
      package org.learn; import java.util.UUID; public class SwissCitizen implements Citizen < public void nationality() < System.out.println("I am Switzerland Citizen"); >public void identity() < System.out.println("My identification number : "+UUID.randomUUID().toString()); >>

      4. MyThread class:

      • We will create concrete thread class extending from JDK Thread class.
      • Complete code of MyThread class is as follows:
      package org.learn; public class MyThread extends Thread < @Override public void run() < System.out.println("Thread started :"); int index = 0; while (index++ < 10) < System.out.println("Iteration "+ index); try < Thread.sleep(300); >catch (InterruptedException e) < break; >> System.out.println("Thread executed successfully"); > >

      5. DemoForClassName class:

Оцените статью