今天做java反射测试,出现此错误,下面是代码:
public class GetClass {
public interface HasBatteries{}
public interface Waterproof{}
public interface Shoots{}
/**
* 默认构造器必须有
* You must define the required default constructor for up.newInstance( ); the
compiler can’t create it because a non-default constructor already exists.
* @author Administrator
*
*/
public static class Toy{
public Toy(){}
public Toy(int i){}
}
}
public class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots {
public FancyToy(){
super(1);
}
}
public class GenericToyTest {
public static void main(String[] args) throws Exception {
Class<FancyToy> ftClass=FancyToy.class;
FancyToy fancy=ftClass.newInstance();
Class<? super FancyToy> up=ftClass.getSuperclass();
Object obj= up.newInstance();
System.out.println(obj);
}
}
Exception in thread "main" java.lang.IllegalAccessException: Class th.GenericToyTest can not access a member of class th.FancyToy with modifiers ""
网上各种查询,说Class前面要必须是public,但是我的就是public;最后各种调试,发现问题出在构造函数这块,构造函数是默认的修饰符,包可见的,
必须改成public,有继承关系的子类父类的构造函数也要修改成public,改完运行ok.