4

I'm looking for some metaprogramming functions in Java analogous to Python's getattr, hasattr, callable etc. If not, is there any good external library for this?

abc def foo bar
  • 2,360
  • 6
  • 30
  • 41
  • 1
    Java has Reflection, but it is nowhere as usable as Python's support for metaprogramming. Languages like Java and C# (especially the former, but also the latter to a lesser extent) were designed under the premise that programmers should not try to be too "clever". – isekaijin Mar 19 '11 at 18:39

4 Answers4

1

As Eduardo commented, you can use reflection. Here's Sun's (Oracle, now) article about it:

http://java.sun.com/developer/technicalArticles/ALT/Reflection/

That should get you heading in the right direction.

Chris Pfohl
  • 18,220
  • 9
  • 68
  • 111
1

Also the JavaBean spec sort of dabbles in this area.

see java.beans.BeanInfo

Also there are libraries such as commons-beanutils that is built on reflection that tries to be more meta-handling-like.

MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66
1

Some of the best "libraries" for metaprogramming take the form of alternative languages that run on the JVM; for example, the Groovy language is a slightly simplified Java with better metaprogramming support (among other features).

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
0

Besides reflection, you may be interested in AOP (e.g., via AspectJ) which allows pre- and/or post-processing of method calls, transformations, interceptions, etc. of various Java execution sequences.

There's no way to intercept calls to methods that don't exist, because such code cannot be compiled.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302