public class Car { String brand; int year; public Car(String brand, int year) { this.brand = brand; this.year = year; } public static void main(String[] args) throws Exception { Car car = Car.class.newInstance(); car.brand = "BMW"; car.year = 2021; System.out.println(car.brand + " " + car.year); } }
public class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public static void main(String[] args) throws Exception { Class personClass = Class.forName("com.example.Person"); Person person = (Person) personClass.newInstance(); person.name = "John"; person.age = 30; System.out.println(person.name + " " + person.age); } }In this example, we have a `Person` class with a constructor that takes name and age parameters. We use the `Class.forName` method to obtain the class object for the `Person` class, and then use the `newInstance` method to create a new instance of the `Person` class. Finally, we set the name and age properties using dot notation, and print out the name and age of the newly created person. Package Library: The `Class` class is part of the `java.lang` package, which is a core Java library package that provides fundamental classes and interfaces. The `forName` method is often used in combination with other library packages, such as `java.sql` for accessing databases or `java.net` for networking. However, the overall package library that the `newInstance` method belongs to is simply the core Java library.