Groovy和元类 [英] Groovy and the Metaclass

查看:96
本文介绍了Groovy和元类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用元类覆盖测试中的静态方法.

I am attempting to use the metaclass to overwrite a static method in a test.

方法是:

org.boon.HTTP.jsonRestCallWithHeaders 

这是Java类,超出了我的控制范围.

It it is a Java class, and it is beyond my control.

声明是:

public static Response jsonRestCallWithHeaders(
            final String url,
            final Map<String, ?> headers
    )

我正尝试通过以下方式使用闭包覆盖该方法:

I am attempting to overwrite the method with a closure via:

HTTP.metaClass.static.jsonRestCallWithHeaders =  { String url, Map<String, ?> headers ->
            if (url.path?.contains('/quotes')) {
                [prop1:value1,
                        prop2: value2 ] as JSON }

但是,当它遇到该重定向请求时,它不会尝试重写该方法.它初始化HTTP类,并尝试调用HTTP.get函数.

However, when it hits that redirect request it doesn't attempt to rewrite the method. It initializes the HTTP class, and attempts to call the HTTP.get function.

我的问题是:为什么对调用HTTP :: get静态方法的jsonRestCallWithHeaders方法的此定义?

My question is: Why is this definition for the jsonRestCallWithHeaders method calling the HTTP::get static method?

stacktrace的图片:

A picture of the stacktrace:

我正在使用Groovy 2.1.9,Grails:2.3.8.该代码正在测试环境中运行.

I am using Groovy 2.1.9, Grails: 2.3.8. The code is being run within a test environment.

推荐答案

我已经测试了以下内容,并且有效:

I have tested the following and it works:

HTTP.getMetaClass().static.jsonRestCallWithHeaders =  { String url, Map<String, ?> headers ->
    // ...
}

这篇关于Groovy和元类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆