简体   繁体   中英

I am trying to create an interface which defines a method getConfiguration which takes in a property(config type) and returns its value

interface ConfigService {
    ConfigValue getConfig(ConfigProperty configProperty);
}

interface ConfigValue<T>{
    T getValue();
} 

interface ConfigProperty<T>{
    ConfigurationProperty<Boolean> ENABLE_SEC_EVAL_LOG = new 
    ConfigurationProperty.Default<>("ENABLE_SEC_EVAL_LOG");

    ConfigurationProperty<Integer> SEC_EVAL_LOG_THRESHOLD = new 
    ConfigurationProperty.Default<>("SEC_EVAL_LOG_THRESHOLD");

    class Default<T> implements ConfigProperty<T> {
        private final String name;

        private Default(final String name) {
            this.name = name;
        }

        @Override
        public String getName() {
            return this.name;
        }  
    }
} 

public class A {
    public static void main() {
        ConfigurationValue cv = getConfiguration(ConfigurationProperty.ENABLE_SEC_EVAL_LOG);
        Boolean abc = cv.getConfigValue();
    }
}  

I want to force getValue to return Boolean if the ConfigProperty type is Boolean.

I want to force getValue to return String if the ConfigProperty type is String.

What am I doing wrong here? Am I not using the generics in the correct way?

You are getting a compile time error on Boolean abc = cv.getValue(); .

When you say "I want to force getValue to return Boolean if the ConfigProperty type is Boolean." you probably mean, you want get rid of this compile time error. Because you cannot force the VM to return another type than the one the returned instance actually has. If you try, you'll get a ClassCastException .

But let's go on. All you need is to add a generic type parameter in the interface ConfigService which will specify the type of the ConfigProperty :

  interface ConfigService {

    <T> ConfigValue<T> getConfig(ConfigProperty<T> configProperty);

  }

Then you can write class A as follows:

  public class A {

    public static void main() {
      ConfigService cs;
      ConfigValue<Boolean> cv = cs.getConfig(ConfigProperty.ENABLE_SEC_EVAL_LOG);
      Boolean abc = cv.getValue();
    }
  }

It didn't work because you've used the raw type of ConfigProperty .


Further reading: What is a raw type and why shouldn't we use it?

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