2

I want to invoke the static method of a class without putting any object in the context of JEXL.

For instance methods, we put an object to the MapContext and use the key to call the method. but In my case, I don't have anything in context. ${person.howYouDoing()} I don't want to use person object to put in the context.

kozmo
  • 4,024
  • 3
  • 30
  • 48
Waqar Babar
  • 109
  • 1
  • 7
  • 1
    Okay... So call the static method. You don't need any instances to call any static method – OneCricketeer Feb 02 '18 at 13:56
  • ... and? What exactly stops you? – PM 77-1 Feb 02 '18 at 13:58
  • for instance methods, we put an object to the MapContext and use the key to call the method. but In my case, I don't have anything in context. '${person.howYouDoing()}' i don't want to use person object to put in the context. – Waqar Babar Feb 02 '18 at 14:05

3 Answers3

2

There's a good discussion of this as a JEXL improvement at https://issues.apache.org/jira/browse/JEXL-140.

The guy who requested this proposed a solution that puts the burden on the JEXL programmer. It creates a String only to get the String class, which is only used to look up the desired class.

${''.class.forName('person').howYouDoing()}

...assuming that "person" is in the default package. This can be used to call static constructors for classes like Pattern for which there is no public constructor:

${''.class.forName('java.util.regex.Pattern').compile('\\d{2}-(\\w{3})-\\d{2}')}

By the way, the JEXL developers suggested subclassing JexlContext to always return any class which exists. This is more elegant than requiring your template writers do the ''.class.forName() hack, but since you didn't want to modify your MapContext, it might not satisfy your question. It also pollutes your context with all classes.

David Costanzo
  • 266
  • 2
  • 6
0

From the documentation:

ns:function A JexlEngine can register objects or classes used as function namespaces. This can allow expressions like: math:cosinus(23.0)

https://commons.apache.org/proper/commons-jexl/reference/syntax.html

So you have to register a class with JexlEngine

Mladen Adamovic
  • 3,071
  • 2
  • 29
  • 44
-3

There is no problem to call a static method from anywhere. Check you have imported the class of the static method and it is in the classpath.

Duhu
  • 28
  • 4
  • are you saying this for JEXL as well? – Waqar Babar Feb 02 '18 at 14:10
  • This is a core functionality of java, it should work everywhere – Duhu Feb 02 '18 at 14:20
  • Are you able to expose the class reference to the JEXL script? If you not, then how could JEXL script call the static method of that class. This question is not about calling a static method of a class in Java, but calling the static method of a class from a JEXL script. – Blessed Geek Sep 26 '19 at 04:07