java 反射 构造器私有化创建对象

  构造器非私有化时
package reflect;

import java.lang.reflect.Constructor;

public class Test {
public static void main(String[] args) throws Exception, NoSuchMethodException {
Class clas = Class.forName("reflect.Single");
System.out.println(clas.newInstance()); }
}


class Single{
public String name = "fuck";

public String get(){
return this.name;
}
}




构造器私有化时
package reflect;

import java.lang.reflect.Constructor;

public class Test {
public static void main(String[] args) throws Exception, NoSuchMethodException {
Class clas = Class.forName("reflect.Single");
Constructor c0 = clas.getDeclaredConstructor();
c0.setAccessible(true);
Single sin = (Single)c0.newInstance();
System.out.println(sin);
}
}


class Single{
public String name = "fuck";
private Single(){
}
public String get(){
return this.name;
}
}

你可能感兴趣的:(反射)