1.使用字节码对象获取该类中定义公用方法。遍历输出该方法名。package step2; public class ReflectFunc { public static void main(String[] args) { Class<Student> studentClass = Student.class; // ---------------------Begin------------------------ // 根据上方的字节码对象,获取定义的方法并遍历输出 // 获取 Student 类中的getAge方法并将其打印输出 // ---------------------End------------------------ } }
时间: 2023-08-15 22:20:12 浏览: 28
package step2;
import java.lang.reflect.Method;
public class ReflectFunc {
public static void main(String[] args) {
Class<Student> studentClass = Student.class;
// 获取Student类中定义的公共方法
Method[] methods = studentClass.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
// 获取指定方法
try {
Method method = studentClass.getMethod("getAge");
System.out.println(method.getName());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
相关问题
1.使用字节码对象获取该类中定义公用方法。遍历输出改方法名。 2.学会使用反射获取类中指定方法
1. 使用字节码对象获取该类中定义公用方法。遍历输出该方法名。
```java
import java.lang.reflect.Method;
public class MyClass {
public void method1() {}
public int method2() { return 0; }
private void method3() {}
protected void method4() {}
public static void main(String[] args) {
Class<?> myClass = MyClass.class;
Method[] methods = myClass.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
}
}
```
输出结果:
```
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
method1
method2
method4
```
2. 学会使用反射获取类中指定方法。
```java
import java.lang.reflect.Method;
public class MyClass {
public void method1() {}
public int method2() { return 0; }
private void method3() {}
protected void method4() {}
public static void main(String[] args) throws Exception {
Class<?> myClass = MyClass.class;
Method method2 = myClass.getMethod("method2");
System.out.println(method2.getName());
}
}
```
输出结果:
```
method2
```
编程要求 根据提示,在右侧编辑器补充代码,完成以下任务: 1.使用字节码对象获取该类中定义公用方法。遍历输出改方法名。 2.学会使用反射获取类中指定方法。package step2; public class ReflectFunc { public static void main(String[] args) { Class<Student> studentClass = Student.class; // ---------------------B
// 1.使用字节码对象获取该类中定义公用方法。遍历输出改方法名。
Method[] methods = studentClass.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
// 2.学会使用反射获取类中指定方法。
try {
Method method = studentClass.getMethod("study", String.class);
System.out.println(method.getName());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}