传递对象子类类型



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

我正在尝试通过getspans()对象"类型"的特定子类。

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, ???); 

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

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

最好使用第二个示例。

您可以通过使用策略模式来实现此功能,而无需诉诸一系列实例。这是一个示例实施,该实施可以使用不同的提供商来计算运输成本,而不必实际知道使用了哪种提供商类型。

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);
    }
}

有关策略模式和完整示例的更多信息。

最新更新