hi guys.. im a java newb and I have some questions about reflection. Here is my code in my driver
Java Code:
public class Driver {
@SuppressWarnings("unused")
public static void main(String[] args) throws InstantiationException, IllegalAccessException
{
String a = "ExamplesPkg.Bicycle";
try {
Class<?> newClass = Class.forName(a);
Constructor<?> [] mountainBicycleConstructors = newClass.getConstructors();
for(Constructor<?> constructors: mountainBicycleConstructors)
System.out.println(constructors);
Cadance meansOfTransport = (Cadance)newClass.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bicycle class
Java Code:
package ExamplesPkg;
public class Bicycle implements Cadance {
// the Bicycle class has
// three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has
// one constructor
public Bicycle(int startCadence, int startSpeed, int startGear)
{
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has
// four methods
public void setCadence(int newValue)
{
cadence = newValue;
}
}
Cadance interface
Java Code:
package ExamplesPkg;
public interface Cadance {
public void setCadence(int newValue);
}
so I created some dummy interface just so I could simulate a situation where you dont know the name of a class that you want to instantiate an object of but you do know that it implents a certain interface. So my driver works well until it gets to the
Java Code:
Cadance meansOfTransport = (Cadance)newClass.newInstance();
line. Clearly my System.out.println(constructors); print public ExamplesPkg.Bicycle(int,int,int). So I got the class that I wanted. Now i just want to create an instance of it and im trying to do that ... but when the object "meansOfTransport" gets created I cannot access the default constructor.
So how can I create an instance of Bicycle like this?
No comments:
Post a Comment