java - 使用python在java代码的方法 block 中添加一行

标签 java python python-3.x python-2.7 code-editor

我有很多 java 文件,我必须在其中搜索一个方法,如果存在,我必须在此方法中添加一行“如果此行尚不存在”。此行必须添加到方法的右大括号之前。

到目前为止,我有以下代码:

import os
import ntpath
extensions = set(['.java','.kt'])
for subdir, dirs, files in os.walk("/src/main"):
        for file in files:
            filepath = subdir + os.sep + file
            extension = os.path.splitext(filepath)[1]
            if extension in extensions:
                if 'onCreate(' in open(filepath).read():
                        print (ntpath.basename(filepath))
                        if 'onPause' in open (filepath).read():
                            print ("is Activity and contains onPause\n")
                            #Check if Config.pauseCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }
                        if 'onResume' in open (filepath).read():
                            print ("is Activity and contains onResume\n")
                            #Check if Config.resumeCollectingLifecycleData(); is in this code bloack, if exists do nothing, if does not exist add to the end of code block before }

但我不确定从这里该何去何从,Python 不是我的第一语言。我可以要求在正确的方向上得到指导吗?

例子: 我正在寻找具有以下签名的方法:

public void onPause(){
   super.onPause();
   // Add my line here
}

public void onPause(){
   super.onPause();
   Config.pauseCollectingLifecycleData(); // Line exists do nothing 
}

最佳答案

这其实挺难的。首先,您的 if "onPause"in sourcecode 方法目前不区分定义 onPause()调用 它。其次,找到正确的结束 } 并非易事。天真地,您可能只计算打开和关闭曲线({ 增加 block 级别,} 减少它),并假设 } 使 block 级别零是该方法的结束 curl 。然而,这可能是错误的!因为该方法可能包含一些 string literal 包含(可能不平衡) curl 。或者用 curl 来评论。这会弄乱 block 级计数。

要正确执行此操作,您必须构建一个实际的 Java 解析器。这是很多工作,即使使用诸如 tatsu 之类的库也是如此。 .

如果您对相当不稳定的 kludge 没问题,您可以尝试使用上面提到的 block 级别计数和缩进作为线索(假设您的源代码缩进得当)。这是我破解的起点:

def augment_function(sourcecode, function, line_to_insert):
    in_function = False
    blocklevel = 0
    insert_before = None
    source = sourcecode.split("\n")
    for line_no, line in enumerate(source):
        if in_function:
            if "{" in line:
                blocklevel += 1
            if "}" in line:
                blocklevel -= 1
                if blocklevel == 0:
                    insert_before = line_no
                    indent = len(line) - len(line.lstrip(" ")) + 4  #4=your indent level
                    break
        elif function in line and "public " in line:
            in_function = True
            if "{" in line:
                blocklevel += 1
    if insert_before:
        source.insert(insert_before, " "*indent + line_to_insert)
    return "\n".join(source)

# test code:
java_code = """class Foo {
    private int foo;
    public void main(String[] args) {
        foo = 1;
    }
    public void setFoo(int f)
    {
        foo = f;
    }
    public int getFoo(int f) {
        return foo;
    }
}
"""
print(augment_function(java_code, "setFoo", "log.debug(\"setFoo\")"))

请注意,这很容易受到各种边缘情况的影响(例如字符串或注释中的 {,或者制表符缩进而不是空格,或者可能有上千种其他情况)。这只是您的起点。

关于java - 使用python在java代码的方法 block 中添加一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53294223/

相关文章:

java - 在应用程序中实现同步和异步行为的有效方法

java - 应用程序关闭时实现 Agora 信号通信

java - 如何在自定义 ClassLoader 中处理类 [B

python-3.x - 当对象传递 typeshed 函数时 Mypy 的行为?

java - 使用 HTML 实体转义字符串时,如果我使用 UTF-8,是否可以安全地跳过 Unicode 127 以上的编码字符?

Python抽象调用基类中导入的库的正确方法

python - 在推理服务中使用 tf.Session 时它是线程安全的吗?

python - Setter dict 就像对象中的属性一样

python-3.x - 检查字符串是否是字符串列表中的子字符串的最快方法

python - 如何在两个相同的类(class)之间只获得一流的数据