You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何方法引用在字节码中生成内部类?其创建时机与存储信息解析

Understanding Lambda Proxy Classes from Method References

Great question—this is a common point of confusion when digging into how Java handles method references under the hood. Let’s break it down clearly:

First: What’s That Inner Class?

The inner class you’re seeing in the bytecode is actually a lambda proxy class. Method references are just syntactic sugar for a specific type of lambda expression, so the JVM treats them the same way: it generates a dynamic proxy class that implements your target functional interface. This class is marked as an inner class in the bytecode metadata, even though it’s generated at runtime, not written in your source code.

When Does the JVM Create Its Object?

The proxy class instance is created the first time the method reference is invoked, via the invokedynamic instruction’s bootstrap method. Here’s the key detail:

  • For stateless method references (like static method references, or instance method references that don’t capture an external object—e.g., String::length), the JVM will often cache the proxy instance. That means after the first call, every subsequent use of the method reference reuses the same object instead of creating a new one.
  • For method references that capture state (like myObj::myMethod, where myObj is an instance from the enclosing scope), a new proxy instance is created each time only if the captured state changes—but if the captured object is fixed, the JVM may still cache it.

What Information Does the Proxy Object Store?

It depends entirely on the type of method reference:

  • Static method references: The proxy object doesn’t store any extra data. Its functional interface method simply delegates directly to the target static method when called.
  • Instance method references (specific object): If you’re referencing a method on a specific instance (e.g., user::getName), the proxy object will store a reference to that user instance as a private field. When the functional interface method is invoked, it uses this stored instance to call the target method.
  • Instance method references (arbitrary object): For references like String::toLowerCase (where the functional interface method accepts a String parameter), the proxy object doesn’t store anything. Instead, when the interface method is called, it uses the parameter passed in as the target object to invoke the method.

Quick Recap

That inner class is the JVM’s runtime-generated proxy for your method reference. Its instance is created on first use (and possibly cached), and it only stores state if it needs to capture a specific object to invoke the target method.

内容的提问来源于stack exchange,提问作者lolcio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:26:06