Location>code7788 >text

Java how to convert Object to the specified Class object

Popularity:751 ℃/2024-09-29 14:52:31

In Java, it's a good idea to set theObjectto the specified type ofClassObjects are actually operations of two different concepts:

  1. commander-in-chief (military)ObjectInstance conversion to a specific type of instance: This usually involves type conversions (e.g.(MyType) myObject) or through the reflection mechanism ((Object)) to carry out.
  2. Getting a specific type ofClassboyfriend: This can be done by.classGrammar or(String className)method implementation.

Since you mentioned "convert Object to specified Class object" may be a bit confusing, I will show the sample code of these two operations separately.

Example 1: Converting an Object Instance to a Type-Specific Instance

First, we define a simple class and a conversion example:

class Animal {
    void eat() {
        ("This animal eats."); }
    }
}

class Dog extends Animal {
    void bark() {
        ("Woof!"); }
    }
}

public class Main {
    public static void main(String[] args) {
        // Assuming we have an instance of Object, which is actually of type Dog
        Object myDog = new Dog();

        // Try to convert the Object to the Dog type
        if (myDog instanceof Dog) {
            Dog dog = (Dog) myDog.
            ().
            (); // Inherits from Animal
        } else {
            ("Not a dog!");
        }

        // Example of using () (actually similar to direct conversion, but more generic)
        try {
            Dog anotherDog = (Dog) ("Dog").cast(myDog); }
            ();
        } catch (ClassNotFoundException e) {
            (); } catch (ClassNotFoundException e) {
        }
    }
}

// Note: The ("Dog") above throws a ClassNotFoundException because "Dog" is not a fully qualified class name.
// The correct way to do this is to use a fully qualified class name, such as "", and this is generally not the recommended way to do dynamic type conversions.

take note of("Dog").cast(myDog)This usage is actually not recommended becausecastmethod is no better than the direct type conversion(Dog) myDogProvide more functionality andFully qualified class names are required.

Example 2: Getting a Class Object of a Specific Type

public class Main {
    public static void main(String[] args) {
        // Use the .class syntax to get the Class object.
        Class<Dog> dogClass = ;
        (()); // Output: (assuming Dog is under the package)

        // Get the Class object using (note the exception handling)
        try {
            Class<? > cls = ("").
            (()); // Same output:
        } catch (ClassNotFoundException e) {
            (); // Same output: } catch (ClassNotFoundException e) {
        }
    }
}

// Assuming the Dog class is under the package

take note ofmethod requires a fully qualified class name and will throw theClassNotFoundException, if the specified class cannot be found. In addition, since thereturnedClass<?>is a wildcard type ofClassobject, so if you know the exact type, it's best to use the.classsyntax to avoid unnecessary type conversions.

The above example shows in detail how to integrate theObjectinstances are converted to instances of a specific type, and how to get the type-specificClassObject.