Answer the question
In order to leave comments, you need to log in
What is the role of the newInstance method in Java?
According to the book Thinking Java, requires you to complete the exercise. So, first of all, I create a top class:
Next, I create several interfaces.public class TOP implements itf2, itf1{}
public interface itf1 {}
public interface itf2 {}
public interface itf3 {}
public class DownA extends TOP implements itf1, itf2 {}
public class DownB extends DownA implements itf1, itf2, itf3{}
public class DownC extends DownB{}
public class MainClass {
private static Formatter f = new Formatter (System.out);
private static void Title (){
f.format("%-15s %10s %10s\n", "Class", "Interface", "Status");
f.format("%-15s %10s %10s\n", "-----", "---------", "------");
}
private static void DataName (Class cc){
f.format("%-15s %10s %10s\n", cc.getName(), " ", " ");
}
private static void DataInterface (Class cc){
f.format("%-15s %10s %10s\n", " ", cc.getName(), cc.isInterface());
}
public static Class ShowDatas (Class cc){
if (cc == null)
System.exit(1);
DataName (cc);
for (Class face : cc.getInterfaces())
DataInterface (face);
f.format("%-15s %10s %10s\n", "-----", "---------", "------");
Class up = cc.getSuperclass();
return ShowDatas (up);
}
public static void main(String[] args) {
Class c = null;
Title ();
try{
c = Class.forName("Demo.DownC");
} catch (ClassNotFoundException e){
e.printStackTrace();
}
ShowDatas (c);
}
}
public class TOP {
private static int counter = 0;
private long id = counter ++;
public String toString (){
return Long.toString(id);
}
}
public class DownClass <T> {
private Class <T> type;
private List <T> mylist;
public DownClass (Class <T> type){
this.type = type;
mylist = Arrays.asList();
}
public List <T> arr (int size){
try {
for (int i=0; i!=size; i++)
mylist.add(type.newInstance());// Добавляем экземпляр класса в массив.
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mylist;
}
}
public class MainClass {
public static void main(String[] args) {
DownClass DC = new DownClass (TOP.class); // Передаем экзепляр класса.
System.out.println(DC.arr(10));
}
}
Answer the question
In order to leave comments, you need to log in
This is reflection. You have an unknown class type Class type. Next, you need to create a new instance of it for this, and dynamic class creation type.newInstance() is used.
Normally, this would be MyDataClass type. and accordingly type = new MyDataClass();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question