In Java, it's a good idea to set theObject
to the specified type ofClass
Objects are actually operations of two different concepts:
-
commander-in-chief (military)
Object
Instance 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. -
Getting a specific type of
Class
boyfriend: This can be done by.class
Grammar 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 becausecast
method is no better than the direct type conversion(Dog) myDog
Provide 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 of:method requires a fully qualified class name and will throw the
ClassNotFoundException
, if the specified class cannot be found. In addition, since thereturned
Class<?>
is a wildcard type ofClass
object, so if you know the exact type, it's best to use the.class
syntax to avoid unnecessary type conversions.
The above example shows in detail how to integrate theObject
instances are converted to instances of a specific type, and how to get the type-specificClass
Object.