Directly initialized final field is not constant folded later when prefix with "this"

Remi Forax forax at univ-mlv.fr
Thu Jun 11 18:29:10 UTC 2020


----- Mail original -----
> De: "Alex Buckley" <alex.buckley at oracle.com>
> À: "compiler-dev" <compiler-dev at openjdk.java.net>
> Envoyé: Jeudi 11 Juin 2020 19:53:54
> Objet: Re: Directly initialized final field is not constant folded later when prefix with "this"

> On 6/11/2020 10:08 AM, Christoph Dreis wrote:
>> Today I experimented around with constant folding and created the following
>> class:
>> 
>> 	private final String world = "world";
>> 
>> 	public String world() {
>> 		return "Hello " + "world";
>> 	}
>> 
>> 	public String worldField() {
>> 		return "Hello " + world;
>> 	}
>> 
>> 	public String worldFieldThis() {
>> 		// This is not constant folded
>> 		return "Hello " + this.world;
>> 	}
> ...
>>    public java.lang.String worldField();
>>      Code:
>>         0: ldc           #14                 // String Hello world
>>         2: areturn
>> 
>>    public java.lang.String worldFieldThis();
>>      Code:
>>         0: aload_0
>>         1: invokestatic  #16                 // Method
>>         java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object;
>>         4: pop
>>         5: ldc           #7                  // String world
>>         7: invokedynamic #22,  0             // InvokeDynamic
>>         #0:makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;
>>        12: areturn
>> 
>> I would have expected to actually see things in worldFieldThis to be constant
>> folded as well.
>> Especially since the field is initialized directly and not anywhere else (e.g.
>> in the constructor).
>> Why is "this" making a difference here?
> 
> `this.world` is not a constant expression. String interning is driven by
> the rules of constant expressions, which are set up for predictability
> in all scenarios not just string concat/interning.
> 
> Alex

and Christoph, you can change the value of a final field by reflection :(

Rémi


More information about the compiler-dev mailing list