[英]How to assign a value to a final static variable from a child inside java?
Suppose we have a hierarchy like this: 假设我们有一个这样的层次结构:
class Parent {
public static final String BASE_NAME = "parent";
public static final String X_URL = BASE_NAME + "/x";
public static final String Y_URL = BASE_NAME + "/y";
}
class ChildA extends Parent {
public static final String BASE_NAME = "childA";
public static final String X_URL = BASE_NAME + "/x";
public static final String Y_URL = BASE_NAME + "/y";
@RequestMapping(value= X_URL)
public String renderXPage(){...}
}
as you can see the X_URL and Y_URL are repeating both in parent and child, if the child can feed in its own BASE_NAME to the parent, we can eliminate redundant repetition of those constants and then we can use them for the annotation value. 如您所见, X_URL和Y_URL在父级和子级中都重复,如果子级可以将其自己的BASE_NAME馈给父级,则可以消除这些常量的多余重复,然后可以将其用作注释值。 How to do this in Java ?
如何在Java中做到这一点?
There is no way to reliable achieve this. 没有办法可靠地实现这一目标。
You can have @RequestMapping
annotation on class and put base part of URL there. 您可以在类上具有
@RequestMapping
批注,然后在其中放置URL的基本部分。
Example: 例:
@RequestMapping("ChildA")
class ChildA {
@RequestMapping(value= "x")
public String renderXPage(){...}
}
renderXPage
will handle "ChildA/x" URL. renderXPage
将处理“ ChildA / x” URL。
Using the solution of @talex I came up with this neat solution: 使用@talex的解决方案,我想到了这个简洁的解决方案:
public interface CommonRelativeUrls {
String X_URL = "/x";
String Y_URL = "/y";
}
public interface Entities {
String CLASS_A = "class-a";
String CLASS_B = "class-b";
...
}
@RequestMapping(value = Entities.CLASS_A)
public class ClassA implements CommonRelativeUrls {
@RequestMapping(value= X_URL)
public String renderXPage(){...}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.