Search code examples
javaconstructorprofilingnew-operatorinvocation

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. 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?

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? (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.


Solution

  • Yes, that is possible through Java Reflection API and other ways as described in this question.

    There are two reflective methods for creating instances of classes: java.lang.reflect.Constructor.newInstance() and Class.newInstance(). The former is preferred.

    Described here: https://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html