1

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.

ammar26
  • 1,584
  • 4
  • 21
  • 41
  • 1
    Superclass constructors. They can be called implicitly, or they can be called with `super(...)` from a subclass's constructor. – ajb Dec 29 '15 at 21:07
  • I don't think this should have been marked as a duplicate. This question asks whether a constructor can be called without `new`; the other question asks how an object can be called without calling a constructor. Two different things. – ajb Dec 29 '15 at 21:08
  • On the other hand, this [see my previous comment] normally happens only if you use **new** on some subclass of the constructor. I'm not completely clear on what you're asking: do you want to know when any constructor is called, or do you want to know when a particular constructor is called? And if you call a constructor and that calls another constructor (implicitly or with `super`), do you count that as two? – ajb Dec 29 '15 at 21:13
  • Im interested to know when any constructor is called. Yes that would be two constructor calls if constructor calls another super constructor. – ammar26 Dec 29 '15 at 21:14

1 Answers1

2

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

Community
  • 1
  • 1
Snusmumrikken
  • 300
  • 1
  • 9