L
Lyndsey.Ferguson
Hello Everyone,
I'm learning Java (using Bruce Eckel's Thinking In Java 3rd Ed) and I'm
in chapter 10 on the Exercises. One of the questions is to use
reflection to create a "Toy" object using the non-default constructor.
Can you comment on how I've done it in the code provided below? I would
like to know if there is a better way. Perhaps to have the program get
the list of constructors and then figure out how to get the correct
parameter list. Comments/Suggestions?
Thanks in advance,
Lyndsey
class Toy {
Toy() {}
Toy(int i) { System.out.println("Creating Toy(" + i + ").");}
}
public class ToyTest {
public static void main(String[] args) {
Class c = null;
try {
c = Class.forName("c10.Toy");
} catch(ClassNotFoundException e) {
System.out.println("Can't find c10.Toy");
System.exit(1);
}
Object o = null;
Object o2 = null;
try {
// Requires default constructor:
o = c.newInstance(); // (*1*)
// Create an object using the non-default constructor
Class[] typeList = { int.class, };
Constructor constructor = cy.getDeclaredConstructor(typeList);
Object[] argList = { new Integer(999), };
o2 = constructor.newInstance(argList);
} catch(Exception e) {
System.out.println("Exception that we are not going to look at
for now.");
System.exit(1);
}
}
} ///:~
I'm learning Java (using Bruce Eckel's Thinking In Java 3rd Ed) and I'm
in chapter 10 on the Exercises. One of the questions is to use
reflection to create a "Toy" object using the non-default constructor.
Can you comment on how I've done it in the code provided below? I would
like to know if there is a better way. Perhaps to have the program get
the list of constructors and then figure out how to get the correct
parameter list. Comments/Suggestions?
Thanks in advance,
Lyndsey
class Toy {
Toy() {}
Toy(int i) { System.out.println("Creating Toy(" + i + ").");}
}
public class ToyTest {
public static void main(String[] args) {
Class c = null;
try {
c = Class.forName("c10.Toy");
} catch(ClassNotFoundException e) {
System.out.println("Can't find c10.Toy");
System.exit(1);
}
Object o = null;
Object o2 = null;
try {
// Requires default constructor:
o = c.newInstance(); // (*1*)
// Create an object using the non-default constructor
Class[] typeList = { int.class, };
Constructor constructor = cy.getDeclaredConstructor(typeList);
Object[] argList = { new Integer(999), };
o2 = constructor.newInstance(argList);
} catch(Exception e) {
System.out.println("Exception that we are not going to look at
for now.");
System.exit(1);
}
}
} ///:~