javareflect反射获取⽅法变量参数类的成员包含变量(Field),⽅法(Method),构造器(Constructor)
类定义
package Reflect;
public class MyTest {
public int a;
public static int b;
public static final int c = 0;
private int d;
public int sum(int a, int b, String c) {
return a + b;
}
public int sub(int a, int b, String c) {
return a - b;
}
MyTest() {
}
MyTest(int a, int b) {
}
}
1.获取变量
package Reflect;
import flect.Constructor;
import flect.Field;
import flect.Method;
import flect.Modifier;
public class Test {
public static void main(String[] args) {
System.out.println(MyTest.class);
final Class<?> clazz = MyTest.class;
System.out.Class());
final Field[] fields = DeclaredFields();
System.out.println("====print fields===");
for (final Field f : fields) {
System.out.Name() + "->");
System.out.Modifiers() + "->");
System.out.Modifiers()));
}
}
输出:
class Reflect.MyTest
class java.lang.Class
====print fields===
a->1->public
b->9->public static
c->25->public static final
d->2->private
2.获取⽅法
package Reflect;
import flect.Constructor;
import flect.Field;
import flect.Method;
import flect.Modifier;
public class Test {
public static void main(String[] args) {
System.out.println(MyTest.class);
final Class<?> clazz = MyTest.class;
System.out.Class());
java反射的作用及应用场景final Field[] fields = DeclaredFields();
System.out.println("====print Method===");
final Method[] ms = Methods();
for (final Method m : ms) {
System.out.println();
System.out.Name() + "==||");
System.out.ReturnType().getName() + "==||");
for (final Class o : m.getParameterTypes()) {
System.out.print(",==" + o.getName());
}
}
}
}
输出:
====print Method===
sum==||int==||,==int,==int,==java.lang.String
sub==||int==||,==int,==int,==java.lang.String
wait==||void==||
wait==||void==||,==long,==int
wait==||void==||,==long
hashCode==||int==||
getClass==||java.lang.Class==||
equals==||boolean==||,==java.lang.Object
toString==||java.lang.String==||
notify==||void==||
notifyAll==||void==||
3.获取构造器
package Reflect;
import flect.Constructor;
import flect.Field;
import flect.Method;
import flect.Modifier;
public class Test {
public static void main(String[] args) {
System.out.println(MyTest.class);
final Class<?> clazz = MyTest.class;
System.out.Class());
System.out.println();
System.out.println("====print Constructor===");
final Constructor[] cs = DeclaredConstructors();
for (final Constructor c : cs) {
System.out.println();
System.out.Name());
for (final Class o : c.getParameterTypes()) {
System.out.print(",==" + o.getName());
}
}
}
}
输出:
====print Constructor===
Reflect.MyTest
Reflect.MyTest,==int,==int

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。