不使用new运算符实例化对象 [英] Instantiate objects without using new operator

查看:221
本文介绍了不使用new运算符实例化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一次Java访谈中,提出以下问题:

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

在java中有一种方法可以在不使用 new的情况下实例化对象运营商?我回答他说没有其他的实例化方法。但他问我如何使用java中的 xml 文件中的配置(在spring框架中)实例化java中的对象。我说,内部弹簧使用 reflection utils 来创建一个带有 new 运算符的对象。但面试官并不相信我的回答。

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.

我看到此链接有用,但有一个 new 运算符间接涉及一个或其他内部方法。

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

有没有办法在不使用 new 运算符的情况下在java中实例化对象?

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

推荐答案

你可以使用来完成Java Reflection API 。这就是Spring框架的DI工作原理(从xml实例化对象)。

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();






此外,
考虑 enum 是一个特殊类,枚举的实例是在不使用 new 运营商。


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

public enum YourEnum { X, Y }

这篇关于不使用new运算符实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆