Search code examples
javacasting

Getting the main class of a java.lang.Object object (T of a Class object?)


I'm wondering how I would get a class from a java.lang.Object object to a specific class, such as a Cat class I may write; not directly casting to Cat, but to automatically get the main class of the object and cast to the main class, since I may take in Object arguments to take in many kinds of classes. Would getting an object through Class<T>, getting T (the type of the main class) be possible?

Here's what I mean:

class Cat {
    public String meowMessage = "meow";

    public void meow() {
        System.out.println(meowMessage);
    }
}

public class Main {
    public static void main(String[] args) {
        Object obj = new Cat();
        // Cat c = obj.getClass()...;
        // ^ how to get the Class object and automatically cast to the main class (Cat)?
    }
}

Solution

  • What you want would involve determining a generic parameter at runtime. This is not possible due to type erasure.