How to access the object of a class without using the class name from a static context in java?

Java 8Object Oriented ProgrammingProgramming

The only possible solution is to get the stack trace of the current thread. Get the class name using an element in the stack trace. Pass it to the forName() method of the class named Class.

This returns a Class object and you can get an instance of this class using the newInstance() method.


public class MyClass {
   String name = "Krishna";
   private int age = 25;
   public MyClass() {
      System.out.println("Object of the class MyClass");
      System.out.println("name: ";
      System.out.println("age: "+this.age);
   public static void demoMethod() throws Exception {
      StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
      StackTraceElement current = stackTrace[1];
   public static void main(String args[]) throws Exception {


Object of the class MyClass
name: Krishna
age: 25
Updated on 05-Aug-2019 14:17:52