检查方法范围Java中的重复变量 [英] Check duplicate variable in a method scope Java
问题描述
我使用包含某些方法的FileReader
读取了Java文件.我如何读取方法范围(方法区域内)以查找重复的变量?
例如,这是我读取的一个Java文件:
public double[] copyArray(double[] data) {
int _nn = data.length;
double[] _tmp = new double[_nn];
System.arraycopy(data, 0, _tmp, 0, _nn);
int _nn;
_nn = tmp;
return _tmp;
}
如何知道方法作用域?,我的意思是在{和}之间,如果找到了作用域,则找到重复的变量,例如上面的示例(int _nn)被重复.
[添加] 我曾尝试使用Java解析器,然后成功.然后,我应该使用列表发送结果,但只能发送列表中的最后一个方法.我的代码有什么问题?
这是MethodVisitor:
private static class MethodVisitor extends VoidVisitorAdapter {
private List<String> list = new ArrayList<String>();
@Override
public void visit(MethodDeclaration n, Object file) {
list.add(n.getName());
}
public List<String> getList() {
return list;
}
}
然后,这是一个调用MethodVisitor的方法:
private MethodVisitor mv;
public void doIt(File file) throws Exception {
CompilationUnit cu;
try {
// parse the file
cu = JavaParser.parse(file);
} finally {
//file.close();
}
// visit and print the methods names
mv = new MethodVisitor();
mv.visit(cu, file);
List<String> list = mv.getList();
for(String item:list){
System.out.println(item);
}
}
1,您需要解析Java代码:
http://code.google.com/p/javaparser/ >
或阅读:
2之后,尝试尝试并显示您的代码
I read java file using FileReader
that contains some method. How i can read method scope (method area inside) to find duplicate variable?
For example, this is a java file that i read:
public double[] copyArray(double[] data) {
int _nn = data.length;
double[] _tmp = new double[_nn];
System.arraycopy(data, 0, _tmp, 0, _nn);
int _nn;
_nn = tmp;
return _tmp;
}
How to know method scope?, i mean between { and }, if scope has found, find duplicate variable such as example above (int _nn) duplicated.
[addition] i have tried using java parser, then is success. Then i should send the results using list, but only last method in the list. What's wrong with my code?
This is a MethodVisitor:
private static class MethodVisitor extends VoidVisitorAdapter {
private List<String> list = new ArrayList<String>();
@Override
public void visit(MethodDeclaration n, Object file) {
list.add(n.getName());
}
public List<String> getList() {
return list;
}
}
Then, this is a method to call MethodVisitor:
private MethodVisitor mv;
public void doIt(File file) throws Exception {
CompilationUnit cu;
try {
// parse the file
cu = JavaParser.parse(file);
} finally {
//file.close();
}
// visit and print the methods names
mv = new MethodVisitor();
mv.visit(cu, file);
List<String> list = mv.getList();
for(String item:list){
System.out.println(item);
}
}
1 you need to parse java code:
http://code.google.com/p/javaparser/
or read this:
Java source code parsers/generators
2 after that, try something and show your code
这篇关于检查方法范围Java中的重复变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!