Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One method to retrieve the .class object in Java while avoiding the use of the class name within a static context is to create an instance of the class using the "new" keyword and then call the getClass() method on the instance. For example:

class MyClass {
  // class definition
}

// in a static context:
MyClass obj = new MyClass();
Class<? extends MyClass> objClass = obj.getClass();

In this example, we create an instance of MyClass called "obj" and then call the getClass() method on it to retrieve the .class object. This approach avoids using the name of the class in a static context, since we are creating an instance of the class rather than referencing it directly.