我是一名Java开发人员。在面试中,我被问到一个关于私有构造函数的问题:
你能访问类的私有构造函数并实例化它吗?
我回答'不可以',但是我的答案是错误的。
你能解释一下我错在哪里,并给出一个使用私有构造函数实例化对象的例子吗?
我是一名Java开发人员。在面试中,我被问到一个关于私有构造函数的问题:
你能访问类的私有构造函数并实例化它吗?
我回答'不可以',但是我的答案是错误的。
你能解释一下我错在哪里,并给出一个使用私有构造函数实例化对象的例子吗?
我的实用类
public final class Example{
private Example(){
throw new UnsupportedOperationException("It is a utility call");
}
public static int twice(int i)
{
int val = i*2;
return val;
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
class Test{
public static void main(String[] args) throws Exception {
int i =2;
final Constructor<?>[] constructors = Example.class.getDeclaredConstructors();
constructors[0].setAccessible(true);
constructors[0].newInstance();
}
}
java.lang.UnsupportedOperationException: It is a utility call
。但是请记住使用反射API会导致额外的开销问题。是的,你可以使用反射
来实例化一个私有构造函数的实例,下面是我从java2s中复制的示例代码,以便更好地理解:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Deny {
private Deny() {
System.out.format("Deny constructor%n");
}
}
public class ConstructorTroubleAccess {
public static void main(String... args) {
try {
Constructor c = Deny.class.getDeclaredConstructor();
// c.setAccessible(true); // solution
c.newInstance();
// production code should handle these exceptions more gracefully
} catch (InvocationTargetException x) {
x.printStackTrace();
} catch (NoSuchMethodException x) {
x.printStackTrace();
} catch (InstantiationException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
}
}
}
class SampleClass1{
private SampleClass1() {
System.out.println("sampleclass cons");
}
public static void createInstance() {
SampleClass1 sc = new SampleClass1();
}
}
public class SingletonDemo {
public static void main(String[] args) {
//SampleClass1 sc1 = new SampleClass1();
SampleClass1.createInstance();
}
}
class SampleClass1{
private SampleClass1() {
System.out.println("sample class constructor");
}
public static SampleClass1 getInstance() {
SampleClass1 sc1 = new SampleClass1();
return sc1;
}
}
public class SingletonDemo {
public static void main(String[] args) {
SampleClass1 obj1 = SampleClass1.getInstance();
}
}
看看单例模式。它使用私有构造函数。
简单的答案是,我们可以在Java中使用私有构造函数。
有各种情况下我们可以使用私有构造函数。主要的情况包括:
我们无法在类外部访问私有构造函数,但是使用Java反射API,我们可以访问私有构造函数。请查看下面的代码:
public class Test{
private Test()
System.out.println("Private Constructor called");
}
}
public class PrivateConsTest{
public void accessPrivateCons(Test test){
Field[] fields = test.getClass().getDeclaredFields();
for (Field field : fields) {
if (Modifier.isPrivate(field.getModifiers())) {
field.setAccessible(true);
System.out.println(field.getName()+" : "+field.get(test));
}
}
}
}
我尝试了这样做,它可以工作。如果我错了,请给我一些建议。
import java.lang.reflect.Constructor;
class TestCon {
private TestCon() {
System.out.println("default constructor....");
}
public void testMethod() {
System.out.println("method executed.");
}
}
class TestPrivateConstructor {
public static void main(String[] args) {
try {
Class testConClass = TestCon.class;
System.out.println(testConClass.getSimpleName());
Constructor[] constructors = testConClass.getDeclaredConstructors();
constructors[0].setAccessible(true);
TestCon testObj = (TestCon) constructors[0].newInstance();
//we can call method also..
testObj.testMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Class A{
private A(){
}
private static createObj(){
return new A();
}
Class B{
public static void main(String[]args){
A a=A.createObj();
}}
因此,要创建此类的对象,其他类必须使用静态方法。
当我们将构造函数设置为私有时,拥有静态方法的意义是什么?
静态方法存在的目的是,在需要创建该类的实例时,可以在创建实例之前应用一些预定义的检查。例如,在单例类中,静态方法会检查实例是否已经被创建。如果实例已经被创建,则只需返回该实例而不是创建新实例。
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
你也可以查看该类是否还有其他公共构造函数。只因为默认构造函数是私有的,并不意味着你不能实例化该类。
var
)存储私有构造函数的实例,而无需使用反射技术。 - ArCiGo