用于记录方法参数的 Idea 实时模板

问题描述 投票:0回答:5

我希望能够在 Jetbrain 的 Idea 中创建一个实时模板来记录方法的参数。我们称之为“大”。它的工作原理如下:

public void get(String one, String two) {
    larg<tab>

创建

public void get(String one, String two) {
    log.info("get: one = " + one + " two = " + two);

我可以输入方法名称,但还没有弄清楚如何提取方法参数。有什么想法吗?

java ide intellij-idea
5个回答
16
投票

我晚了 4 年,但预定义的模板 soutp 几乎使用 groovyscript 变量来完成此操作。

这是一个很棒的脚本,可以满足您的需求

groovyScript("'\"' + _1.collect { it + ' = [\" + ' + it + ' + \"]'}.join(', ') + '\"'", methodParameters())

0
投票

看起来目前无法使用实时模板。

来自 Jetbrain 论坛

There is no predefined live template function to do this for you automatically.
You can write a plugin that would provide such a function.

0
投票

这是我的绝妙脚本

groovyScript("import com.intellij.psi.*;import com.intellij.psi.util.PsiTreeUtil; def file = PsiDocumentManager.getInstance(_editor.project).getPsiFile(_editor.document); PsiMethod method = PsiTreeUtil.findElementOfClassAtOffset(file, _editor.caretModel.offset, PsiMethod.class, false); PsiParameter[] parameters = method == null ? PsiParameter.EMPTY_ARRAY : method.parameterList.parameters; return parameters.size() == 0 ? '' : '\"' + method.name + ' : ' + parameters.collect { def prefix = it.name + ' = '; def type = it.type; return type instanceof PsiArrayType ? type.componentType instanceof PsiPrimitiveType ? prefix + '\" + java.util.Arrays.toString(' + it.name + ')' : prefix + '\" + java.util.Arrays.deepToString(' + it.name + ')' : prefix + '\" + ' + it.name }.join(' + \", ')", methodParameters())

0
投票

在 Kotlin 的 Android Studio 中,我使用它来记录类名、方法名和参数。
我使用我的名字作为标签来轻松地在 logcat 中进行过滤。我主要使用这些来调试,我不会用我的名字提交这些消息。

Log.d("MYNAME", "$CLASS_NAME$:$METHOD_NAME$: $PARAMETERS$")

然后参数定义如下。

CLASS_NAME
kotlinClassName()

METHOD_NAME
kotlinFunctionName()

PARAMETERS
groovyScript("'' + _1.collect { it + ' = $' + it}.join(', ') ", functionParameters())

如果在主要活动中使用这将是结果

 fun aFunctionWithParameters( first: Int, second: String, third: ArrayList<String>){
        Log.d("MYNAME", "MainActivity:aFunctionWithParameters: first = $first, second = $second, third = $third")
    }

我的解决方案基于 Rob 的答案,并根据我的需要进行了编辑。


0
投票

groovyScript("def params = _3.collect {it + ' = " + ' + it + ' + "'}.join(', '); return '"' + _1 + ' :: ' + _2 + '( ) >>' + (params.empty ? '' : ': ' + params) + '"'", kotlinClassName() , kotlinFunctionName(), functionParameters())

这将打印:

Log.d(TAG, "MyClassName :: myMethodName() >>: param1 = " + param1 + ", parma2 = " + parma2 + "");

请参阅此图片了解如何添加此内容:https://i.stack.imgur.com/aHwgl.png

© www.soinside.com 2019 - 2024. All rights reserved.