- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to access the object of a class without using the class name from a static context in java?
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.
Example
public class MyClass { String name = "Krishna"; private int age = 25; public MyClass() { System.out.println("Object of the class MyClass"); System.out.println("name: "+this.name); System.out.println("age: "+this.age); } public static void demoMethod() throws Exception { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); StackTraceElement current = stackTrace[1]; Class.forName(current.getClassName()).newInstance(); } public static void main(String args[]) throws Exception { demoMethod(); } }
Output
Object of the class MyClass name: Krishna age: 25
- Related Articles
- How to access Static variable of Outer class from Static Inner class in java?
- How static class Object is created without reference of outer class in java?
- How to access the members of a class from another class in Java?
- How to access the private methods of a class from outside of the class in Java?
- How to access variables from enclosing class using lambda in Java?
- How to call a non-static method of an abstract class from a static method in java?
- Is it possible to create a class without a name in Java?
- How to access a derived class member variable by an interface object in Java?
- How to prevent object of a class from garbage collection in Java?
- Create a Date object using the Calendar class in Java
- Static class in Java
- What is a static class in Java?
- Listing the Modifiers of a Class Object in Java
- What are static members of a Java class?
- Display the package name of a class in Java

Advertisements