5

Is it possible to check if a library exist before importing it in Java. For instance you have a code:

if (library.java exists) import library

Charles
  • 50,943
  • 13
  • 104
  • 142
df611
  • 143
  • 11
  • 1
    Can you tell us why you need to do this? – HariKrishnan Aug 07 '13 at 11:50
  • The reason I want to do this is because I have a function that generates some code (other functions) and later in my program I want to use those other functions so I have to check before using them if they exist – df611 Aug 07 '13 at 15:09
  • Looks like what you need is byte code manipulation. Please take a look at CGLib and JavaAssist. Libraries like hibernate use similar techniques to generate code at run time. Hope that was helpful. – HariKrishnan Aug 07 '13 at 16:36

1 Answers1

1

No, it is not possible do do a conditional import.

Eric Stein
  • 13,209
  • 3
  • 37
  • 52
  • 5
    It's not **literally** possible to make `import`, itself, conditional, but it's certainly possible to get essentially the same end result. This one-liner "no you can't do that" is, at best, *incredibly* incomplete. – T.J. Crowder Aug 07 '13 at 11:48
  • That depends on how you define "the end result". You can't conditionally make the namespace available to the class file. – Eric Stein Aug 07 '13 at 11:51
  • @T.J.Crowder In retrospect, I may have fixated on "import" as literally being the "import" keyword. Rereading, that still looks like his intent to me, but I can also see your position. Clearly classes can be loaded in to the classloader conditionally. It might have been nice if the OP was more clear. – Eric Stein Aug 07 '13 at 13:25