Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java methods with varargs identified as transient?

Tags:

I was playing with Java Reflection API and observed that methods with variadic argument list become transient. Why is that and what does transient keyword mean in this context?

From Java Glossary, transient:

A keyword in the Java programming language that indicates that a field is not part of the serialized form of an object. When an object is serialized, the values of its transient fields are not included in the serial representation, while the values of its non-transient fields are included.

However this definition does not say anything about methods. Any ideas?

import java.lang.reflect.Method; import java.lang.reflect.Modifier;  public class Dummy {     public static void main(String[] args) {         for(Method m : Dummy.class.getDeclaredMethods()){             System.out.println(m.getName() + " --> "+Modifier.toString(m.getModifiers()));         }     }      public static void foo(int... args){} } 

Outputs:

main --> public static foo --> public static transient 
like image 722
ahmet alp balkan Avatar asked Feb 08 '11 18:02

ahmet alp balkan


People also ask

Can a method be transient in Java?

Transient in Java is used to indicate that a field should not be part of the serialization process. The modifier Transient can be applied to member variables of a class to turn off serialization on these member variables. Every field that is marked as transient will not be serialized.

What is varargs in java?

Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments. Variable Arguments in Java simplifies the creation of methods that need to take a variable number of arguments.


2 Answers

Sort of an answer can be found in the code of javassist AccessFlag

public static final int TRANSIENT = 0x0080; public static final int VARARGS   = 0x0080; 

It appears both have the same values. And since transient means nothing for methods, while varargs means nothing for fields, it is ok for them to be the same.

But it is not OK for the Modifier class not to take this into account. I'd file an issue about it. It needs a new constant - VARARGS and a new method - isVarargs(..). And the toString() method can be rewritten to include "transient/varargs".

like image 66
Bozho Avatar answered Sep 28 '22 09:09

Bozho


This looks like a bug in the implementation. I think that the root cause might be that the bit set in the .class file for transient fields is the same for varargs methods (see http://java.sun.com/docs/books/jvms/second_edition/ClassFileFormat-Java5.pdf, pages 122 and 119).

like image 44
templatetypedef Avatar answered Sep 28 '22 10:09

templatetypedef