如何解决“java.lang.InstantiationException”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29189895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:32:58  来源:igfitidea点击:

How to resolve a "java.lang.InstantiationException"?

javaxmlclassloadersaxinstantiationexception

提问by Brian J

I'm parsing in an XML file using SAX but when I call the class loader on the class, a java.lang.InstantiationExceptionis thrown.

我正在使用 SAX 解析 XML 文件,但是当我在类上调用类加载器时,java.lang.InstantiationException抛出了 a 。

I debugged this by the reason for the exception, 'Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.'

我根据异常原因对此进行了调试,'当应用程序尝试使用类 Class 中的 newInstance 方法创建类的实例时抛出,但无法实例化指定的类对象,因为它是接口或抽象类。 '

But the locationclass isn't an interface or abstract class. I've also checked that the class is in the correct package and it is.

location该类不是接口或抽象类。我还检查了该类是否在正确的包中,并且确实如此。

Does anyone have any idea why the exception is being thrown in this case?

有谁知道为什么在这种情况下抛出异常?

The exception is being thrown just after the first println in the startElement of the Parser class:

在 Parser 类的 startElement 中的第一个 println 之后抛出异常:

public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
        if (qName.equals("location")){
            location = true;

            System.out.println("Found a location...");
            //exception thrown after this statement as shown
            //in the error output below
            try {
                //Read in the values for the attributes of the element <location>
                int locationID = Integer.parseInt(atts.getValue("id"));
                String locationName = atts.getValue("name");

                //Generate a new instance of Location on-the-fly using reflection. The statement Class.forName("gmit.Location").newInstance(); invokes the 
                //Java Class Loader and the calls the null (default) constructor of Location.
                Location loc = (Location) Class.forName("gmit.Location").newInstance();
                loc.setId(locationID); //Now configure the Location object with an ID, Name, Description etc...
                loc.setName(locationName);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }else if (qName.equals("description")){
            description = true;
            System.out.println("Found a description. You should tie this to the last location you encountered...");
        }else if (qName.equals("exits")){
            exits = true;
            System.out.println("Found an exit. You should tie this to the last location you encountered...");
        }else if (qName.equals("item")){
            item = true;
            System.out.println("Found an item. You should tie this to the last game-character you encountered if the boolean gameCharacter flag is true...");
        }else if (qName.equals("game-character")){
            gameCharacter = true;
            System.out.println("Found a game character...");
        }else if (qName.equals("search-algorithm")){
            searchAlgorithm = true;
            System.out.println("Found a search algo. You should tie this to the last game-character you encountered if the boolean gameCharacter flag is true...");
        }
    }

My complete location class:

我的完整位置类:

http://hastebin.com/yofuyafipe.java

http://hastebin.com/yofuyafipe.java

The errors being thrown during run time:

运行时抛出的错误:

http://hastebin.com/jonozeyefe.avrasm

http://hastebin.com/jonozeyefe.avrasm

采纳答案by Stephen C

Your Locationclass does not have a no-args constructor. (It has two constructors with declared arguments ... so there is no default no-args constructor.)

您的Location类没有无参数构造函数。(它有两个带有声明参数的构造函数......所以没有默认的无参数构造函数。)

Solutions:

解决方案:

  • Add a no-args constructor.
  • Reflectively lookup one of the Constructorobjects on the Location Classobject and invoke it using Constructor.newInstance(...)with arguments that give the actual constructor argument values.
  • 添加无参数构造函数。
  • 反射性地查找ConstructorLocationClass对象上的对象之一,并使用Constructor.newInstance(...)提供实际构造函数参数值的参数调用它。

It looks like the first option is the better one in this context ... 'cos it looks like you don't have the required argument values at that point in the code.

在这种情况下,看起来第一个选项是更好的选项......'因为看起来你在代码中的那个点没有所需的参数值。

回答by zee

Thanks Stephen C.

谢谢斯蒂芬 C。

Caused by: java.lang.reflect.UndeclaredThrowableException: null
    at org.springframework.util.ReflectionUtils.handleReflectionException(ReflectionUtils.java:120) ~[spring-core-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper.getBean(BeanWrapperFieldSetMapper.java:250) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
    at org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper.mapFieldSet(BeanWrapperFieldSetMapper.java:196) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
    at org.springframework.batch.item.file.mapping.DefaultLineMapper.mapLine(DefaultLineMapper.java:43) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
    at org.springframework.batch.item.file.FlatFileItemReader.doRead(FlatFileItemReader.java:180) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
    ... 50 common frames omitted
Caused by: java.lang.InstantiationException: com.example.batchprocessing.Price
    at java.lang.Class.newInstance(Class.java:427) ~[na:1.8.0_131]
    at org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper.getBean(BeanWrapperFieldSetMapper.java:247) ~[spring-batch-infrastructure-4.1.2.RELEASE.jar:4.1.2.RELEASE]
    ... 53 common frames omitted

Adding public Price(){};to Price class, fixed the issue (BTW, this is a springbatch based app).

添加public Price(){};到价格类,修复了问题(顺便说一句,这是一个基于 springbatch 的应用程序)。

public class Price {

    private String x;
    private String y;

    public Price(){};

    public price(String x, String y) { this.x = x ; this.y = y; };

~
~
~

}