This content has been marked as final. Show 8 replies
Each of the classes must take an int argumentEach of the classes must take a long argument, to agree with the constructor for Event.
Class eventClass = Class.forName(event);Class<? extends Event> eventClass = (Class<? extends Event>)Class.forName(event);
Constructor ctor = eventClass.getConstructor(Integer.class);Constructor<? extends Event> ctor = eventClass.getConstructor(long.class);
//Right here I don't know what to call to get the LightOff class to startlong delay = 5555L; // or whatever
Event event = ctor.newInstance(delay);
ejp wrote:This should probably be
Constructor<? extends Event> ctor = eventClass.getConstructor(long.class);
Constructor<? extends Event> ctor = eventClass.getConstructor(Long.TYPE);
Thanks, both work.
Thanks and sorry for correcting what I thought was a typo.
I did not know this syntax is valid (since when? autoboxing?).
Now I know.
Since 1.1 as far as I know. I was certainly using in the 1990s.
This was working great, but now I am having a weird issue.
I moved the call to each Event object into it's own method and now when I compile the program I get this:
Note: GreenhouseControls.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
So if I recompile with -Xlint I get this:
GreenhouseControls.java:159: warning: [unchecked] unchecked cast
found : java.lang.Class<capture#532 of ?>
required: java.lang.Class<? extends tme3.Event>
Class<? extends Event> eventClass = (Class<? extends Event>)Class.forName(className);
There is an arrow pointing to the className in brackets on the last line.
className is a String for the class in which I am going to call, ex. LightOff
That's because Class.forName() returns a Class<?>. Not much you can do about this except @SuppressWarnings("unchecked").
There's a way to make the check explicit:
This way the check is actually done at that line (in the asSubclass() method) and you can avoid the ugly @SupressWarnings.
Class<? extends Event> eventClass = Class.forName(className).asSubclass(Event.class);