1.使用字节码对象获取该类中定义公用方法。遍历输出改方法名。 2.学会使用反射获取类中指定方法
时间: 2023-12-03 12:44:21 浏览: 38
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
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)