这是我的文件(更新):
import java.lang.reflect.*;
public class ClassExtract {
public void printClassDefinition (String[] args){
try {
Class cls = Class.forName(args[0]);
Field fieldlist[]
= cls.getDeclaredFields();
for (int i
= 0; i < ((fieldlist.length + 1) - (fieldlist.length)); i++)
{
Field fld = fieldlist[i];
System.out.println("+ " + fld.getDeclaringClass().toString().replaceAll("class", ""));
System.out.println("------");
}
for (int j = 0; j < fieldlist.length; j++) {
Field fld1 = fieldlist[j];
int mod = fld1.getModifiers();
System.out.println(Modifier.toString(mod).toString().replaceAll("public", "+")
.replaceAll("private", "-").replaceAll("protected", "#") + " " +
fld1.getType() + " " + fld1.getName());
}
}
catch (Throwable e) {
System.err.println(e);
}
}
public static void main(String args[])
{
new ClassExtract().printClassDefinition(args);
}
}
我应该读这个文件:
public class Complex{
private int re;
private int im;
public Complex(int re, int im){
this.re = re;
this.im = im;
}
public Complex add(Complex h){
return new Complex(this.re+h.re, this.im+h.im);
}
public Complex sub(Complex h){
return new Complex(this.re-h.re, this.im-h.im);
}
public String toString(){
if (im >= 0){
return re +" + " +im + "i";
}
else return re +" " +im + "i";
}
public static void main(String[] args){
Complex c1 = new Complex(5,1);
Complex c2 = new Complex(5,0);
System.out.printf("c1 = %s, c2 = %s\n", c1, c2);
System.out.printf("c1 + c2 = %s\n", c1.add(c2) );
}}
它应该生成类似的东西:
(+) Complex
***
(-) int re
(-) int im
***
(+) Complex(re:int, im:int)
(+) add():Complex
(+) sub():Complex
(+) toString():String
(+) main()
由于我的文件遍历,我在行之后得到“re”和“int”的打印,例如,我的格式一般搞砸了。我可以使用所有可能的帮助。感谢。
答案 0 :(得分:3)
对不起,我担心你的代码距离解决方案还有几英里远,给你发正确的答案就好像作弊......我会建议你采用以下方法。