Close

Java Reflection - Class.newInstance() Examples

Code Snippets Java Reflection Java 


Class:

java.lang.Class

java.lang.Objectjava.lang.Objectjava.lang.Classjava.lang.Classjava.io.SerializableSerializablejava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.TypeTypejava.lang.reflect.AnnotatedElementAnnotatedElementLogicBig

Method:

public T newInstance()
              throws InstantiationException,
                     IllegalAccessException

Returns a newly allocated instance of the class represented by this object. The class is instantiated as if by a new expression with an empty argument list.


Examples


package com.logicbig.example.clazz;

public class NewInstanceExample {

public static void main(String... args) throws IllegalAccessException, InstantiationException {
Thread t = Thread.class.newInstance();
System.out.println(t);
}
}

Output

Thread[Thread-0,5,com.logicbig.example.clazz.NewInstanceExample]




package com.logicbig.example.clazz;

import java.io.Serializable;

public class NewInstanceExample2 {

public static void main(String... args) throws IllegalAccessException, InstantiationException {

Serializable s = new Serializable() {};
System.out.println(s);
Serializable b = s.getClass().newInstance();
System.out.println(b);
}
}

Output

com.logicbig.example.clazz.NewInstanceExample2$1@fa958b9
com.logicbig.example.clazz.NewInstanceExample2$1@c90273




package com.logicbig.example.clazz;

import java.io.Serializable;

public class NewInstanceExample3 {

public static void main(String... args) throws IllegalAccessException, InstantiationException {
Serializable serializable = Serializable.class.newInstance();
System.out.println(serializable);
}
}

Output

Caused by: java.lang.InstantiationException: java.io.Serializable
at java.base/java.lang.Class.newInstance(Class.java:545)
at com.logicbig.example.clazz.NewInstanceExample3.main(NewInstanceExample3.java:13)
... 6 more
Caused by: java.lang.NoSuchMethodException: java.io.Serializable.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3322)
at java.base/java.lang.Class.newInstance(Class.java:530)
... 7 more




See Also