该程序编译并没有给出错误。当我在最新的 Netbeans(安装了最新的 Java)中运行程序时,我看不到输出。我从 Java 7 第三版第 5 章中获取了代码的想法。讨论的主题是使用 java.lang.class 和创建对象而不使用 new 运算符。
package java7thirdeditionpart1;
public class creatObjectWithoutNewOperator {
public static void main(String[] args) {
Class myClass2 = null;
try {
myClass2 = Class.forName("Book");
} catch (ClassNotFoundException e) {
}
if (myClass2 != null) {
try {
//Creating an instance of the Book class
Book book1 = (Book) myClass2.newInstance();
book1.setAuthor("Khan");
System.out.println(book1.getAuthor());
book1.setTitle("Second Book");
book1.setIsbn("kh_s_b");
book1.printBookDetails();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (InstantiationException e2) {
e2.printStackTrace();
}
}
}//main method ends here.
}//class creatObjectWithoutNewOperator ends here.
package java7thirdeditionpart1;
public class Book {
String isbn;
String title;
String author;
public Book()
{
this.setIsbn("");
this.setTitle("");
this.setAuthor("");
}//Constructor ends here.
public Book(String isbn, String title, String author) {
this.setIsbn(isbn);
this.setTitle(title);
this.setAuthor(author);
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public void printBookDetails(){
System.out.println("*********************");
System.out.println("ISBN: " + this.getIsbn());
System.out.println("Title: " + this.getTitle());
System.out.println("Author: " + this.getAuthor());
System.out.println("*********************");
}//method printBookDetails ends here.
}//Class Book ends here.