账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    如何在接口实现类的方法中,获取在该方法所属的接口中定义的常量;
    40
    0

    如何在接口实现类的方法中,获取在该方法所属的接口中定义的常量;

    public interface RequireValidator {
        Integer errno = 456;
        Boolean required();
    }
    
    public interface TypeValidator {
        Integer errno = 123;
        Boolean isInteger();
    }
    
    public class Validator implements RequireValidator, TypeValidator  {
        @Override
        public Boolean require() {
            // 此处如何获取456
            return null;
        }
    
        @Override
        public String isInteger() {
            // 此处如何获取123;
            return null;
        }
    }
    

    如上,如何在注释处获取对应的值?求大神解答!!!

    我的思路如下:

    1. 获取类实现的所有的接口;
    2. 遍历接口列表,查找定义了该方法的接口;
    3. 然后通过确定了的接口直接访问errno

    这样的问题是如何判断接口是否定义了当前方法?

    有更好的实现方法请指出,本人小白,求帮助!!!

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 暖夏清风 普通会员 1楼

      在Java中,你可以通过反射来获取方法所属的接口中定义的常量。以下是一个简单的示例:

      ```java import java.lang.reflect.Method;

      public class Main { public static void main(String[] args) throws Exception { // 获取方法信息 Method method = YourInterface.class.getMethod("yourMethod");

          // 获取方法对应的接口
          YourInterface yourInterface = (YourInterface) method.getDeclaringClass();
      
          // 获取方法所属的常量
          String yourConstant = yourInterface.getConstant("yourConstantName");
      
          System.out.println("Your constant is: " + yourConstant);
      }
      

      } ```

      在这个示例中,你需要替换YourInterface为你的接口的名称,yourMethod为你的方法的名称,yourConstantName为你的常量的名称。

      注意,如果你的接口中没有定义常量,那么反射将会抛出NoSuchMethodException。在这种情况下,你需要在接口的定义中添加常量。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部