javaclassreflection

What is the difference between a.getClass() and A.class in Java?


In Java what pros/cons exist surrounding the choice to use a.getClass() or A.class? Either can be used wherever a Class<?> is expected, but I imagine that there would be performance or other subtle benefits to using both in different circumstances (just like there are with Class.forName() and ClassLoader.loadClass().


Solution

  • I wouldn't compare them in terms of pros/cons since they have different purposes and there's seldom a "choice" to make between the two.

    In terms of performance, there may be a measurable difference, but I won't say anything about it because in the end it is JVM and/or compiler dependent.