java-tips

问题列表

  1. How do I invoke a Java method when given the method name as a string?
  2. Can you instantiate an interface in Java?

How do I invoke a Java method when given the method name as a string?

我意识到这个问题好像是一个关键,是rmi调用的关键

public class HelloWorld {
    public void sayHello(){
        System.out.println("ceshai");
    }

}

  HelloWorld helloWorld = new HelloWorld();

        try {
            Method method = helloWorld.getClass().getMethod("sayHello");
            method.invoke(helloWorld);
        }catch(Exception error){
            error.printStackTrace();
        }

下面的这段代码是motan里面的一种跳用机制

@Override
    public Response invoke(Request request) {
        DefaultResponse response = new DefaultResponse();

        Method method = lookupMethod(request.getMethodName(), request.getParamtersDesc());

        if (method == null) {
            MotanServiceException exception =
                    new MotanServiceException("Service method not exist: " + request.getInterfaceName() + "." + request.getMethodName()
                            + "(" + request.getParamtersDesc() + ")", MotanErrorMsgConstant.SERVICE_UNFOUND);

            response.setException(exception);
            return response;
        }

        boolean defaultThrowExceptionStack = URLParamType.transExceptionStack.getBooleanValue();
        try {
            Object value = method.invoke(proxyImpl, request.getArguments());
            response.setValue(value);
        } catch (Exception e) {
            if (e.getCause() != null) {
                response.setException(new MotanBizException("provider call process error", e.getCause()));
            } else {
                response.setException(new MotanBizException("provider call process error", e));
            }

            // not print stack in error log when exception declared in method
            boolean logException = true;
            for (Class<?> clazz : method.getExceptionTypes()) {
                if (clazz.isInstance(response.getException().getCause())) {
                    logException = false;
                    defaultThrowExceptionStack = false;
                    break;
                }
            }
            if (logException) {
                LoggerUtil.error("Exception caught when during method invocation. request:" + request.toString(), e);
            } else {
                LoggerUtil.info("Exception caught when during method invocation. request:" + request.toString() + ", exception:" + response.getException().getCause().toString());
            }
        } catch (Throwable t) {
            // 如果服务发生Error,将Error转化为Exception,防止拖垮调用方
            if (t.getCause() != null) {
                response.setException(new MotanServiceException("provider has encountered a fatal error!", t.getCause()));
            } else {
                response.setException(new MotanServiceException("provider has encountered a fatal error!", t));
            }
            //对于Throwable,也记录日志
            LoggerUtil.error("Exception caught when during method invocation. request:" + request.toString(), t);
        }

        if (response.getException() != null) {
            //是否传输业务异常栈
            boolean transExceptionStack = this.url.getBooleanParameter(URLParamType.transExceptionStack.getName(), defaultThrowExceptionStack);
            if (!transExceptionStack) {//不传输业务异常栈
                ExceptionUtil.setMockStackTrace(response.getException().getCause());
            }
        }
        // 传递rpc版本和attachment信息方便不同rpc版本的codec使用。
        response.setRpcProtocolVersion(request.getRpcProtocolVersion());
        response.setAttachments(request.getAttachments());
        return response;
    }

Can you instantiate an interface in Java?

我真的佩服,英语为什么有这么准确的表达力
https://www.remwebdevelopment.com/blog/can-you-instantiate-an-interface-in-java-373.html

java中可以实例化一个接口吗?答案是不可以的。
Can you instantiate an interface in Java? The answer is no, but you might see some code examples that cause you to scratch your head and question your understanding of the rule. Lets say we have this interface:

public interface MyInterface{
  public void myMethod();
}

You can actually create an anonymous class that implements this interface like this:

MyInterface myInterface = new MyInterface(){
  @Override
  public void myMethod(){
    //some code goes here...
  }
};

When I was first learning Java this really confused me. But what’s really going on is that you are creating an anonymous inner class that implements the interface. And you can get away with instantiating it like this because you are providing the implementation to satisfy the contract of the interface. Note that the @Override annotation simply tells the compiler to make sure you are using the same signature as the method that is declared in MyInterface.


太有魅力了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值