在两种情况下抛出该异常(来自docs):
类对象表示抽象类,接口,数组类,基元类型或void
该类没有无效的构造函数
基于a simple test I did,在您的情况下,问题是生成的匿名类没有一个无效的构造函数。
测试代码:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
{
Test thing = new Test(){ public void update(){ id="updated"; } };
thing.update();
Test thang = thing.getClass().newInstance();
System.out.println( thing.id+" "+thang.id );
}
{
Test2 thing = new Test2("name"){ public void update(){ id="updated"; } };
thing.update();
Test2 thang = thing.getClass().newInstance();
System.out.println( thing.id+" "+thang.id );
}
}
}
abstract class Test{
public String id;
Test(){ id = "Empty"; }
abstract public void update();
}
abstract class Test2{
public String id;
Test2(String me){ id = me; }
abstract public void update();
}第一个测试(使用Test)运行正常,第二个测试(使用Test2)在newInstance调用中失败,但该异常。