传递对象的子类类型

时间:2014-01-21 22:40:15

标签: java android class casting

我正在使用一个将类类型作为参数的函数:

我试图将getSpans()传递给Object“type”的特定子类。

Spannable ss;
Object type;
int start;
int end;

//Assume above variables properly initialized.
....

//getSpans(int start, int end, Class<T> type)
ss.getSpans(start, end, ???); 

2 个答案:

答案 0 :(得分:1)

是的,只需使用type.class即可。它将返回类型变量的Class对象。另请尝试type.getClass().class

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

更好地使用第二个例子。

答案 1 :(得分:0)

您可以通过使用策略模式来实现此功能,而无需使用一系列instanceof。下面是一个示例实现,使用不同的提供程序计算运费,而不必实际知道使用的提供程序类型。

public enum ShippingMethod {
    FIRST_CLASS {
        public double getShippingCost(double weightInPounds, double distanceInMiles) {
            // Calculate the shipping cost based on USPS First class mail table
        }
    },
    FED_EX {
        public double getShippingCost(double weightInPounds, double distanceInMiles) {
            // Calculate the shipping cost based on FedEx shipping
        }       
    },
    UPS {
        public double getShippingCost(double weightInPounds, double distanceInMiles) {
            // Calculate the shipping cost based on UPS table
        }           
    };

    public abstract double getShippingCost(double weightInPounds, double distanceInMiles);
};

public class ShippingInfo {

    private Address address;
    private ShippingMethod shippingMethod = ShippingMethod.FIRST_CLASS;

    public Address getAddress() {
        return this.address;
    }

    public double getShippingCost(double weightInPounds, double distanceInMiles) {
        return shippingMethod.getShippingCost(weightInPounds, distanceInMiles);
    }
}

有关Strategy Patternfull example的更多信息。