java.lang.instantiationexception-reflection mechanism

Source: Internet
Author: User

Package com.test.classtest;

public class Test {

public static void Main (string[] args) throws Exception {
String hl = "Hello";
String sm = "Smile";
String word = "world";
World wr= null;

Hello hello = new Hello (HL);
Smile Smile = new Smile (SM);


/*WR = Hello;

Wr.setsmile (smile);

Wr.output (HL);
Wr.changewords (SM, HL);
Wr.getsmile (). Smile (Word); */
World World = New World (word);
Smile se = (Smile) class.forname ("Com.test.classtest.Smile"). newinstance ();

}

}

Exception in thread "main" java.lang.InstantiationException: Com.test.classtest.Smile
At Java.lang.Class.newInstance (class.java:427)
At Com.test.classtest.test.main (test.java:23)
Caused by: Java.lang.NoSuchMethodException:com.test.classtest.Smile. ()
At Java.lang.Class.getConstructor0 (class.java:3082)
At Java.lang.Class.newInstance (class.java:412)

Three points to confirm this question:

1. Regardless of whether the class in Class.forName ("Com.test.classtest.Smile") is under the same package as the main function, write the full name of the class: package name + class name;

2. An instantiated object is an interface or class that cannot be instantiated, such as an abstract class

3. When instantiating an object using class reflection, this error can also occur if the object does not contain a parameterless constructor, and the workaround is to add an empty parameterless constructor to this class that is instantiated by class reflection.

Other:

There is a clear requirement in hibernate that each persisted class must have a constructor with no arguments.

It is stated here that if you declare a constructor with parameters in the class, the parameterless constructor is automatically overwritten so that the system cannot invoke the parameterless constructor instantiation class, so this error occurs.

java.lang.instantiationexception-reflection mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.