Unnecessary Object Allocation for getClass()
ID |
java.new_instance_for_getclass |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
best-practice, efficiency |
Description
Reports expressions like new Foo().getClass() that allocate a throwaway object solely to obtain its Class instance. The class literal Foo.class achieves the same result without an unnecessary heap allocation and constructor execution.
Rationale
Creating an object instance just to call getClass() on it is wasteful. The constructor may have side effects or be expensive, and the allocated object is immediately discarded. The .class literal is a compile-time constant that incurs zero runtime cost.
Anonymous inner classes (new Foo() { … }.getClass()) are excluded because their runtime class is a compiler-generated subclass whose .class literal is not directly accessible.
// Wasteful -- allocates an object just to get its Class
Class<?> clazz = new StringBuilder().getClass();
String name = new ArrayList<>().getClass().getName();