Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

java - Instantiate objects without using new operator

In one of the java interview, the following question is asked:

In java is there a way to instantiate an object without using new operator? I replied to him that there is no other way of instantiation. But he asked me how an object in java is instantiated with the configurations in an xml file in java(in spring framework). I said, internally the spring uses reflection utils to create an object with a new operator. But the interviewer was not convinced with my answer.

I saw this link to be useful but there is a new operator indirectly involved in one or the other internal methods.

Is there really a way to instantiate objects in java without using new operator?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it using the Java Reflection API. That's how the Spring framework's DI works (instantiating object from xml).

Class<YourClass> c = YourClass.class;
YourClass instance = c.newInstance();

Also, Considering enum to be a special class, the instances of the enum are created without using new Operator.

public enum YourEnum { X, Y }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...