PHP __call equivalent for java

后端 未结 5 968
醉梦人生
醉梦人生 2021-02-07 10:11

Is there a Java equivalent for the __call of PHP?

It would make sense to me if that\'s not the case, because it would probably result in compiler errors.

From th

相关标签:
5条回答
  • 2021-02-07 10:45

    This sort of dynamic method/attribute resolution which is common in dynamically typed languages such as PHP, Python and Ruby is not directly supported in the Java language.

    The effect can be approximated using Dynamic Proxies which requires you to have an interface for which the implementation will be dynamically resolved. Third party libraries such as CGLIB allow similar things to be done with normal Java classes.

    This API based, special case interception of method invocation is not as convenient as the direct, always on support you can get with __call in PHP or equivalent features in other dynamically typed languages (such as __getattr__ in Python). This difference is due the fundamentally different ways in which method dispatch is handled in the two types of languages.

    0 讨论(0)
  • 2021-02-07 10:49

    No, Java doesn't have that feature. For one thing, I think it would make overloading pretty much impossible (some argue overloading is a bad idea anyway, but this isn't the right forum for that debate). Beyond that, I get the sense that the designers of Java just feel that the flexibility something like that (I know it from Perl where it's called AUTOLOAD) is outweighed by the guarantee that any code that compiles is only calling methods that actually exist (barring binary incompatibilities).

    0 讨论(0)
  • 2021-02-07 10:58

    No, there is not.

    0 讨论(0)
  • 2021-02-07 11:03

    No, java is a compiled language and the compiler wants to make sure that every function you call actually exists.

    0 讨论(0)
  • 2021-02-07 11:04

    as other said, java doesn't support this.

    it does have something called a proxy class which can intercept calls to known methods (rather than undefined methods as in php's __call()). a proxy can be created dynamically as a wrapper around any interface:

    http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html#proxy

    http://java.sun.com/j2se/1.4.2/docs/guide/reflection/proxy.html#examples

    Foo foo = (Foo) DebugProxy.newInstance(new FooImpl());
    foo.bar(null);
    

    foo looks like a Foo, but all the calls are intercepted by FooImpl's invoke() method.

    to create a truly de novo class at runtime with dynamic methods in its interface, you can essentially compile a class definition and use java's class loader to import it at runtime. a tool like apache's JCI or Arch4J can handle this for you. still, the class will only have those methods you specify.

    0 讨论(0)
提交回复
热议问题