简体   繁体   中英

Java: Generics won't work for my method, what else can I do?

In the code below, I would like the second method to be generic, too, but since I create the Calendar object inside the method, because of type erasure , I don't see how . One possibility would be to pass in the Calendar object, but that would defeat the main purpose for having this method at all (not having to think about the Calendar objects).

How can I make the second method work for multiple subclasses of Calendar, like the first method does?

public static <U extends Calendar> CalendarMatch<U> tpFromCalendar(U dt)
{
    // we want to do all comparisons on UTC calendars
    dt.setTimeZone(TimeZone.getTimeZone(DEFAULT_TZ_ID));
    return new CalendarMatch<U>(dt);
}

public static CalendarMatch<GregorianCalendar> tpDailyGregorian(int h)
{
    GregorianCalendar dt = new GregorianCalendar(TimeZone.getTimeZone(DEFAULT_TZ_ID));
    dt.clear();
    dt.set(Calendar.HOUR, h);

    // this works because of type inference
    return tpFromCalendar(dt);
}

There is absolutely no need to use reflection here. So don't!

public static <U extends Calendar> CalendarMatch<U> tpDailyGregorian(
    int h, CalendarFactory<U> factory
) {
    Calendar dt = factory.create(TimeZone.getTimeZone(DEFAULT_TZ_ID));
    dt.clear();
    dt.set(Calendar.HOUR, h);

    // this works because of type inference
    return tpFromCalendar(dt);
}

Where:

public interface CalendarFactory<U extends Calender {
     U create(TimeZone timeZone);
}

The signature could be:

public static <U extends Calendar> CalendarMatch<U> tpDailyGregorian(int h, Class<? extends U> clazz);

One way would be to use reflection to instantiate your calendar (passing in the Calendar type):

Constructor<? extends U> c = clazz.getContructor(TimeZone.class);
U dt = c.newInstance(TimeZone.getTimeZone(DEFAULT_TZ_ID));

Of course, with this dt instance, you can only call methods on Calendar and not GregorianCalendar

dt.clear();
dt.set(Calendar.HOUR, h);

Date d = dt.getGregorianChange(); //CANNOT CALL THIS!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM