0

I came across some code that uses reflection to get to the "path" variable in the FileInputStream!! Weirder part is that commons.lang.reflect.FieldUtils.readField(is, "path", true) throws a java.lang.IllegalArgumentException. That too intermittently... May be some specific scenario leads to that, but I am not able to figure out. Any pointers as to what could cause reflection to fail to "see" the Field?

The code is buried in lot of Cascading workflows related mumbo jumbo but here is the relevant part -

//This same method is invoked multiple times on same file. If it matters?
    method(SourceCall<Object, InputStream> sc) {
        InputStream is = sc.getInput();
        if (is instanceof FileInputStream) {
             FileInputStream fileInputStream = (FileInputStream)is;
             //The line below throws IllegalArgumentException - sometimes
             String fileName = (String)FieldUtils.readField(fileInputStream , "path", true);
             return fileName;
         }
    }
user2023507
  • 1,153
  • 12
  • 23
  • Why do you need the path to the FileInputStream? According to following source, FileInputSteam does not contain a _path_ field and the readField will throw an IllegalArgumentException if ` if ...the field name is blank or empty or could not be found`: http://www.docjar.com/html/api/java/io/FileInputStream.java.html – copeg Apr 28 '15 at 21:52
  • I am staring at the 1.7.0_60_64 version of java.io.FileInputStream and it has the following - private final String path; Looks like the fileName is extracted out of path variable and used downstream. Still working on the cascading API part to figure out why it has to be this way! – user2023507 Apr 28 '15 at 22:00
  • Again, why do you need the path? Reflection seems like a shaky way to go about it. – copeg Apr 28 '15 at 22:06
  • Not interested in alternative solutions to the larger problem. Just curious as to why reflection would fail to see the field in this case. I will refactor original code anyway to avoid this error. Want to know if there exists a way to fix it instead. Thanks! – user2023507 Apr 28 '15 at 22:17
  • 1
    Turns out to be a problem with bamboo that is building project. It is setting java version 1.7.0_21 instead of 1.7.0_51 as the java.home maven environment variable and FileInputStream does not have "path" variable in version 1.7.0_21..! To know more about release plugin & java.home refer to http://stackoverflow.com/questions/3638399/maven-release-plugin-specify-java-compiler-version – user2023507 Apr 29 '15 at 21:11

1 Answers1

0

You should user FieldUtils.readDeclaredField(...) to get access to private fields.

dmitrievanthony
  • 1,501
  • 1
  • 15
  • 41
  • No. readDeclaredField only considers the target class, whereas, readField considers parent classes as well. Has nothing to do with private/public access. – user2023507 Apr 29 '15 at 18:14