How to Create Class Object in Java


In this example we will show two methods to create an object of a Class in Java.

Source Code

1)Using Class.forName()

package com.beginner.examples;

public class OptionDialogExample {

    public static void main(String[] args){
    	try 
    	{
			Class example = Class.forName("com.beginner.examples.FileExample");
		} 
    	catch (ClassNotFoundException e) 
    	{
			e.printStackTrace();
		}
        System.out.println("Done!");
    }
}

Output:

Done!

2) Using ClassLoader

package com.beginner.examples;

public class ClassExample2 {

    public static void main(String[] args){
    	try 
    	{
    		ClassLoader cl = ClassLoader.getSystemClassLoader();
    		Class  example = cl.loadClass("com.beginner.examples.FileExample");
		} 
    	catch (ClassNotFoundException e) 
    	{
			e.printStackTrace();
		}
        System.out.println("Done!");
    }
}

Output:

Done!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments