java如何调用函数
调用静态方法
静态方法属于类而非实例,可直接通过类名调用。语法为 ClassName.methodName(parameters)。
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
// 调用
int result = MathUtils.add(3, 5); // 输出 8
调用实例方法
实例方法需通过对象调用。需先创建类的实例,再使用 objectName.methodName(parameters)。

public class Calculator {
public int multiply(int a, int b) {
return a * b;
}
}
// 调用
Calculator calc = new Calculator();
int result = calc.multiply(4, 6); // 输出 24
方法重载调用
同一类中允许同名方法存在,需参数列表不同(类型、数量或顺序)。调用时根据传入参数自动匹配。
public class Printer {
public void print(String text) {
System.out.println("String: " + text);
}
public void print(int number) {
System.out.println("Int: " + number);
}
}
// 调用
Printer printer = new Printer();
printer.print("Hello"); // 输出 "String: Hello"
printer.print(42); // 输出 "Int: 42"
递归调用
方法内部调用自身,需设置终止条件避免无限循环。

public class Factorial {
public static int factorial(int n) {
if (n == 0) return 1; // 终止条件
return n * factorial(n - 1); // 递归调用
}
}
// 调用
int result = Factorial.factorial(5); // 输出 120
通过反射调用
运行时动态获取方法并调用,适用于不确定方法名的场景。
import java.lang.reflect.Method;
public class ReflectionExample {
public static void callMethod(Object obj, String methodName) throws Exception {
Method method = obj.getClass().getMethod(methodName);
method.invoke(obj); // 调用无参方法
}
}
// 示例类
class Sample {
public void greet() {
System.out.println("Hello via Reflection!");
}
}
// 调用
Sample sample = new Sample();
ReflectionExample.callMethod(sample, "greet"); // 输出 "Hello via Reflection!"
Lambda表达式调用
适用于函数式接口(仅含一个抽象方法的接口),简化匿名类实现。
interface Greeter {
void greet(String name);
}
// 调用
Greeter greeter = name -> System.out.println("Hello, " + name);
greeter.greet("Alice"); // 输出 "Hello, Alice"
注意事项
- 静态方法调用无需实例化,实例方法必须先创建对象。
- 递归需谨慎处理终止条件,避免栈溢出。
- 反射调用可能抛出异常(如
NoSuchMethodException),需捕获或声明。 - Lambda表达式要求目标接口为函数式接口(如
Runnable、Consumer等)。






