プログラムはコンパイルされ、エラーは発生しません。最新の Netbeans (最新の Java インストール済み) でプログラムを実行すると、出力が表示されません。Java 7 Third Edition の第 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.