简体   繁体   English

构造函数调用绑定到Java中的new关键字?

[英]Constructor invocation bound to new keyword in Java?

I'm working on Java Code Profiling where I need to know how many times a method has invoked a constructor in source code. 我正在研究Java代码剖析,需要知道一个方法在源代码中调用了多少次构造函数。 So far the easiest way is to scan for new keyword and count that how many times constructor has been invoked. 到目前为止,最简单的方法是扫描关键字并计算构造函数被调用的次数。 I would like to know is there any possibility where a constructor can be invoked without the new keyword? 我想知道在没有new关键字的情况下可以调用构造函数的可能性吗?

Also if I'm only scanning for new keyword and binding it with constructor invocation only, it is possible that new keyword can also be used for some other purpose besides constructor invocation? 另外,如果我仅扫描new关键字并将其仅与构造函数调用绑定,那么new关键字是否可以用于构造函数调用以外的其他用途? (in that case my constructor invocation count could be wrong if such statement occurs in code) (在那种情况下,如果这样的语句出现在代码中,我的构造函数调用计数可能是错误的)

Edit: I want to increase the count when any constructor is called. 编辑:我想增加任何构造函数被调用时的计数。

Yes, that is possible through Java Reflection API and other ways as described in this question . 是的,可以通过Java Reflection API和此问题中描述的其他方式来实现。

There are two reflective methods for creating instances of classes: java.lang.reflect.Constructor.newInstance() and Class.newInstance(). 有两种创建类实例的反射方法:java.lang.reflect.Constructor.newInstance()和Class.newInstance()。 The former is preferred. 前者是首选。

Described here: https://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html 在此处描述: https//docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM