不使用new运算符实例化对象

编程入门 行业动态 更新时间:2024-10-15 20:20:38
本文介绍了不使用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运算符实例化对象

本文发布于:2023-11-30 08:51:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649431.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   实例   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!