我有一个包含
的java文件a.java
int ab( fg)
abs
bcd
abs
int x,y;
现在我希望区分int
变量和int
方法,并将其存储在不同的数组中,将输出存储为变量:a
b
和方法:{{1但我很困惑如何区分两者..
ab
答案 0 :(得分:1)
java中的反射允许您在运行时获取有关该类的信息。反射包具有多个方法/字段/接口等类。 这里有一个例子......
import java.lang.reflect.Method;
import java.lang.reflect.Field;
class DummyClass
{
public int x;
public int z;
public int meathod1()
{ return 1;
}
public int meathod2()
{ return 2;
}
public int method3()
{ return 3;
}
}
class MainClass
{
public static void main(String...s)
{
//Step 1: Getting the object of the class whose Fields/method u want to get.
DummyClass obj=new DummyClass();
//Step 2. Getting the Class of the class whose field/method u want to get.You can skip Step 1 if u already have Object the class.
Class myClass=obj.getClass();
//Step 3.Class has some multiple inbuilt methods to get the methods and Fields of any class.
Method[] methodList=myClass.getDeclaredMethods();
/*Now u have all the Methods you have declared in the class.The length of the methodList is the no of declared methods u have in your class.If u want to get the inherited methods too,then use getMethods() instead of getDeclaredMethods(),but then all your methods must be public then because getMethods() returns only public methods.*/
System.out.println("Total No of Methods : "+methodList.length);
//Step 4. Class has some other Inbuild methods that return Fields.
Field[] fieldList=myClass.getDeclaredFields();
System.out.println("Total no of Fields : "+fieldList.length);
}
}
答案 1 :(得分:0)
为了计算int变量和int方法,您需要了解可以声明方法和变量的可能方法。
变量和方法都可以有访问者(私有,公共或受保护),静态,最终和很快。
区分int变量和方法的特征是:
1)int变量声明不包含开括号和右括号,并且总是有; 例如: int num = 0;
但是你需要小心: =后面可能有一个括号。例如: int num = getNum();
2)方法声明将始终包含开括号和右括号,并且始终具有}或;最后。
例如:
案例1:
int getNum(){
}
案例2:
int getNum(); //abstract or interface
然而,可能会有一些复杂的情况,例如:
int
getNum(
)
{
} //<--- this is a valid function even through there is new line