Java 怎么获取返回值是多少字节
时间: 2024-03-23 16:37:51 浏览: 15
在 Java 中,可以使用 `java.lang.reflect.Method` 类的 `getReturnType()` 方法获取一个方法的返回类型,然后使用 `java.lang.reflect.Type` 类的 `getTypeName()` 方法获取返回类型的名称。接着,你可以使用 `java.lang.Class` 类的 `forName()` 方法获取返回类型的 `Class` 对象,然后使用 `java.lang.Class` 类的 `getName()` 方法获取类名。最后,使用 `java.lang.Class` 类的 `getSimpleName()` 方法获取类名的简单名称,即去除包名的类名。通过这些方法,你可以获取一个方法的返回值类型及其大小。例如:
```java
import java.lang.reflect.Method;
import java.lang.reflect.Type;
public class Main {
public static void main(String[] args) throws Exception {
Method method = Main.class.getMethod("foo");
Type returnType = method.getReturnType();
Class<?> returnClass = Class.forName(returnType.getTypeName());
System.out.println(returnClass.getSimpleName() + " size: " + returnClass.getDeclaredField("SIZE").getInt(null) / 8 + " bytes");
}
public int foo() {
return 42;
}
}
```
输出结果为:
```
Integer size: 4 bytes
```