问题
Im using Android Annotations Framework, specially for Rest Integration. I have the following code.
An interface for Host configuration
public interface Host {
public String URL = "http://192.168.2.137";
}
And the annotated Interface for Rest communication.
@Rest(rootUrl = Host.URL, converters = { MappingJacksonHttpMessageConverter.class })
public interface RestClient {
@Get("/entities.json")
Entity[] allEntities();
}
and my question is, Why the value for annotation attribute Rest.rootUrl must be a constant expression? and how can i use a String resource for Rest.rootUrl ?
I wish to do something like
@EBean
public class Host{
@StringRes
String URL;
}
But is impossible with the RestClient interface.
The idea is to handle a localized rest application, suppose distinct URLs by language
http://en.myapp.com
http://es.myapp.com
I know that an Java Interface must have final properties, but, there are a way to handle a localized rootUrl value?
Thanks.
回答1:
Jon is right about annotation values, but Android Annotations actually does give you a way to dynamically set the root url for a RestClient.
Just omit the rootUrl attribute from the annotation and add a method to the interface:
void setRootUrl(String rootUrl);
Just remember that you'll need to call RestClient.setRootUrl(url)
at some point in your app before you actually use RestClient.
More info at https://github.com/excilys/androidannotations/wiki/Rest%20API#rest
回答2:
Why the value for annotation attribute Rest.rootUrl must be a constant expression?
This isn't really an Android question in particular, or about those specific annotations. All annotation values in Java have to be constant expressions - because those values are baked into the classfile at compilation time.
From the JLS section 9.7:
An element type T is commensurate with an element value V if and only if one of the following conditions is true:
- T is an array type E[] and either:
- V is an ElementValueArrayInitializer and each ElementValue (analogous to a VariableInitializer in an array initializer) in V is commensurate with E; or
- V is an ElementValue that is commensurate with E.
- The type of V is assignment compatible (§5.2) with T, and furthermore:
- If T is a primitive type or String, and V is a constant expression (§15.28).
- V is not null.
- If T is Class, or an invocation of Class, and V is a class literal (§15.8.2).
- If T is an enum type, and V is an enum constant.
来源:https://stackoverflow.com/questions/15972574/why-the-value-for-annotation-attribute-rest-rooturl-must-be-a-constant-expressio