将抽象类存储在数组列表中

时间:2015-08-19 10:46:15

标签: java abstract-class

我想存储几个类的类对象,这些类在数组列表中扩展抽象类。请注意,我必须使用抽象类而不使用接口,因为类Country将包含更多功能。

我的想法是稍后访问这个类对象,创建它们的对象并调用方法。

问题:如何实现这一点,因为以下代码会产生错误。

import java.util.ArrayList;

public class Main
{
    public static void main(String args[]) {
        new Main();
    }

    public Main() {
        // The idea is to add the class of all specific countries to the countries array
        ArrayList<Class<Country>> countryclasses = new ArrayList<Class<Country>>();

        // Doesn't work
        countryclasses.add(England.class);

        // Doesn't work
        Class<Country> englandclass = England.class; // Error
        countryclasses.add(englandclass);

        // Doesn't work
        England england = new England();
        Class<Country> country = england.getClass().getSuperclass().getClass();
        // Class<Country> country = england.getClass().getSuperclass().getClass();
        countryclasses.add(country);

        for(Class<Country> countryclass : countryclasses) {
            // Create an object from the class
            // Call the getName() method
        }
    }

    public abstract class Country {
        abstract String getName();
    }

    public class England extends Country {
        public String getName() {
            return "England";
        }
    }
}

1 个答案:

答案 0 :(得分:6)

如果你真的想要List<Class>而不是使用多态的实例集合,可以使用upper-bounded wildcard来定义将Country或扩展它的类:

List<Class<? extends Country>> countryclasses = new ArrayList<Class<? extends Country>>();
Class<? extends Country> englandclass = England.class;
countryclasses.add(englandclass);