instantiate a Class by its name - Java Reflection

Java examples for Reflection:Class

Description

instantiate a Class by its name

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String clazz = "java2s.com";
        System.out.println(instantiate(clazz));
    }//w  w  w.  java2 s  . c o m

    public static Object instantiate(String clazz) {

        try {
            Class<?> c = Class.forName(clazz);
            return c.newInstance();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}

Related Tutorials