简体   繁体   中英

How to implement a parameterized interface at runtime?

I have checked into Java proxy's and cglib, but I haven't found any examples about how I would even go about starting this project.

Here is what I need to do.

I have an interface:

public interface RoadMap<T extends City>{
    public void map(T city);
}

I have a bunch of different types of cities as inner classes of a class called Cities

I want to be able to implement the interface at run time by looping through the different inner classes of the Cities class like so:

for(Class clazz : Cities.class.getDeclaredClasses()){
   //implement RoadMap interface 
}

All of the implementations will be identical, except for the type parameter needs to be that of type clazz (in the for loop).

Is this even possible? If so where should I start. Java Proxies and cglib talk alot about method intercepting, but that is not really what I want to do here.

Thanks

If all the implementations are identical, you just need a single implementation. Here's such an implementation which doesn't care about generic types, not using a dynamic proxy (but you could do the same using a dynamic proxy):

public class RoadMapFactory {
    @SuppressWarnings("unchecked")
    public <T extends City> RoadMap<T> createWithRawTypes() {
        return new RoadMap() {
            @Override
            public void map(City city) {
                System.out.println("I mapped this city : " + city);

            }
        };
    }

    public static void main(String... args) {
        RoadMapFactory factory = new RoadMapFactory();
        RoadMap<SubCity1> map1 = factory.createWithRawTypes();
        map1.map(new SubCity1());
        RoadMap<SubCity2> map2 = factory.createWithRawTypes();
        map2.map(new SubCity2());
    }
}

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