PHP __call equivalent for java - java

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 the PHP manual on magic methods:
__call() is triggered when invoking inaccessible methods in an object context.

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.

No, there is not.

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.

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).

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

Related

Minimizing interfaces in Golang

In golang, interfaces are extremely important for decoupling and composing code, and thus, an advanced go program might easily define 1000s of interfaces .
How do we evolve these interfaces over time, to ensure that they remain minimal?
Are there commonly used go tools which check for unused functions ?
Are there best practices for annotating go functions with something similar to java's #Override, which ensures that a declared function is properly implementing a expected contract?
Typically in the java language, it is easy to keep code tightly bound to an interface specification because the advanced tooling allows us to find and remove functions which aren't referenced at all (usually this is highlighted automatically for you in any common IDE).
Are there commonly used go tools which check for unused functions ?
Sort of, but it is really hard to be sure for exported interfaces. oracle can be used to find references to types or methods, but only if you have all of the code that references you availible on your gopath.
can you ensure a type implements a contract?
If you attempt to use a type as an interface, the compiler will complain if it does not have all of the methods. I generally do this by exporting interfaces but not implementations, and making a constructor:
type MyInterface interface{
Foo()
}
type impl struct{}
func (i *impl) Foo(){}
func NewImpl() MyInterface{
return &impl{}
}
This will not compile if impl does not implement all of the required functions.
In go, it is not needed to declare that you implement an interface. This allows you to implement an interface without even referencing the package it is defined in. This is pretty much exactly the opposite of "tightly binding to an interface specification", but it does allow for some interesting usage patterns.
What your asking for isn't really a part of Go. There are no best practices for annotating that a function satisfies an interface. I would personally say the only clear best practice is to document which interfaces your types implement so that people can know. If you want to test explicitly (at compile time) if a type implements an interface you can do so using assignment, check out my answer here on the topic; How to check if an object has a particular method?
If you're just looking to take inventory of your code base to do some clean up I would recommend using that assignment method for all your types to generate compile time errors regarding what they don't implement, scale down the declarations until it compiles. In doing so you should become aware of the disparity between what might be implemented and what actually is.
Go is also lacking in IDE options. As a result some of those friendly features like "find all references" aren't there. You can use text searching tricks to get around this, like searching func TheName to get only the declaration and .TheName( to get all invocations. I'm sure you'll get used to it pretty quickly if you continue to use this tooling.

When is a reference to the object class required?

What is the function of the class Object in java? All the "objects" of any user defined class have the same function as the aforementioned class .So why did the creators of java create this class?
In which situations should one use the class 'Object'?
Since all classes in Java are obligated to derive (directly or indirectly) from Object, it allows for a default implementation for a number of behaviours that are needed or useful for all objects (e.g. conversion to a string, or a hash generation function).
Furthermore, having all objects in the system with a common lineage allows one to work with objects in a general sense. This is very useful for developing all sorts of general applications and utilities. For example, you can build a general purpose cache utility that works with any possible object, without requiring users to implement a special interface.
Pretty much the only time that Object is used raw is when it's used as a lock object (as in Object foo = new Object(); synchronized(foo){...}. The ability to use an object as the subject of a synchronized block is built in to Object, and there's no point to using anything more heavyweight there.
Object provides an interface with functionality that the Java language designers felt all Java objects should provide. You can use Object when you don't know the subtype of a class, and just want to treat it in a generic manner. This was especially important before the Java language had generics support.
There's an interesting post on programmers.stackexchange.com about why this choice was made for .NET, and those decisions most likely hold relevance for the Java language.
What Java implements is sometimes called a "cosmic hierarchy". It means that all classes in Java share a common root.
This has merit by itself, for use in "generic" containers. Without templates or language supported generics these would be harder to implement.
It also provides some basic behaviour that all classes automatically share, like the toString method.
Having this common super class was back in 1996 seen as a bit of a novelty and cool thing, that helped Java get popular (although there were proponents for this cosmic hierarchy as well).

Would it be possible to have "method/field" literals comparable to the class literals in Java/Scala?

Java's Foo.class as well Scala's classOf[Foo] literal class syntax return a reflective view about the class in question.
Is it possible and would it make sense to provide something like .method/.field or methodOf[]/fieldOf[] for getting comparable reflective access to methods and fields?
How would something like this be implemented in Java/Scala?
In the case of Java, I would assume that this would either require a language change (very unlikely) or some wizardry with bytecode tools/AspectJ, whereas in Scala it is probably possible to implement it with an implicit conversion.
Yes and no. Paul Phillips has certainly expressed an interest in such a thing, and there's a lot of work currently happening in trunk around the forthcoming scala reflections.
It's doubtful that we'll see anything like your proposed syntax though. Methods are not a first-class construct and, as such, and only be referenced via their containing class. But we will be getting a nice scala-friendly way to access members via reflection, including default params, parameter names, etc.
I don't recall where, but I stumbled across a Java library recently that would take Java classes as input and generate a metaclass, so to speak, that had static fields (I think) that were references to all of the fields and methods on the target class. It's certainly not as elegant as what you're looking for, but it struck me as a potentially useful bit of wizardry.

Why all the java code is packed in Classes?

I have started learning Java and picked up some books and collected materials online too. I have programmed using C++. What I do not understand is that ,even the main method is packed inside a Class in Java. Why do we have everything packed inside some class in Java ? Why it does not have independent functions ?
This is the main concept of object oriented programming languages: everything is an object which is an instance of a class.
So because there's nothing but classes in Java (except the few Java primitive types, like int, float, ...) we have to define the main method, the starting point for a java application, inside a class.
The main method is a normal static method that behaves just like any other static method. Only that the virtual machine uses this one method (only) to start the main thread of the application.
Basically, it works like this:
You start the application with java MyClass
The JVM loads this class ("classloading")
The JVM starts a new thread (the main thread)
The JVM invokes the method with the signature public static void main(String[])
That's it (in brief).
Because that's how the designers of the language wanted it to be.
Java enforces the Object Oriented paradigm very very heavily. That said, there are plenty of ways to work around it if you find it cumbersome.
For one, the class that contains main can easily have lots of other methods in it. Also, it's not uncommon to make a class called 'Utility' or something similar to store all your generic methods that aren't associated with any particular class or objects.
If you work in a smart IDE such as eclipse, you'll eventually find that Java's seemingly over-abundant restrictions, exceptions, and rigorous structure are actually a blessing in disguise. The compiler can understand and work through your code much better when the language isn't cluttered with syntactic junk. It will give you information about unused variables and methods, dead code, etc. and the IDE will give you suggested fixes and code completion (and of course auto-format). I never actually type out import statements anymore, I just mouse over the code and select the class I want. With rigorous types, generic types, casting restrictions etc. the compiler can catch a lot of code which might otherwise result in all kinds of crazy undetectable behavior at runtime. Java is the strictest language in the sense that most of what you type will not compile or else very quickly throw an Exception of one kind or another.
So, if you ask a question about the structure of Java, Java programmers will generally just answer "because that's the rule" while Python programmers are trying to get their indentation right (no auto-format to help), Ruby programmers are writing unit tests to make sure all their arguments are of the correct type and C programmers are trying to figure out where the segfault is occuring. As I understand C++ has everything Java has, but too many other capabilities (including casting anything to anything and oh-so-dangerous pointer arithmetic).
And you can have multiple entry points in a jar depending on how many classes inside the package has main.

Inject New Methods and Properties into Classes During Runtime

Is there any way we can inject new methods and properties into classes during run-time.
http://nurkiewicz.blogspot.com/2009/09/injecting-methods-at-runtime-to-java.html states we may do that by using Groovy.
Is it possible by just doing using Java?
Is it possible by just doing using
Java?
The simple answer is an emphatic "You don't want to do that!".
It is technically possible, but not without resorting to extremely complex, expensive and fragile tricks like bytecode modification1. And even then, you have to rely on dynamic loading to access the modified type and (probably) reflection to make use of its new members. In short, you would be creating lots of pain for yourself, for little if any gain.
Java is a statically typed language, and adding / modifying class type signatures can break the static typing contract of a class.
1 - AspectJ and the like allow you to inject additional behaviour into a class, but it is probably not the "runtime" injection that you are after. Certainly, the injected methods won't be available for statically compiled code to call.
So if you were really crazy, you could do something like what they outline here. What you could do is load the .java file, find the correct insertion point, add whatever methods you need to, call the java compiler and reload the class. Good luck debugging that mess though :)
Edit This actually might be of some use...
You can do some quite funky things with AOP, although genuine modification of classes at runtime is a pretty hairy technique that needs a lot of classloading magic and sleight of hand.
What is easier is using AOP techniques to generate a subclass of your target class and to introduce new methods into this instead, what AOP called a "mixin" or "introduction". See here to read how Spring AOP does it, although this may be quite lame compared to what you're actually trying to achieve.
Is it possible by just doing using Java?
Quite so, the "only" thing you have to do is define an instrumentation agent which supplies an appropriate ClassFileTransformer, and you'll have to use reflection to invoke the added methods. Odds are this isn't what you want to do, though, but it's doable and there's a well-defined interface for it. If you want to modify existing methods you may be interested in something like AspectJ.
While it might be possible, it is not useful.
How would you access these new fields and methods?
You could not use these methods and fields directly (as "ordinary" fields and methods), since they wouldn't be compiled in.
If all you want is the possibility to add "properties" and "methods", you can use a Map<String, Object> for the "dynamic properties", and a Map<String, SuitableInterface> for the "dynamic methods", and look them up by name.
If you need an extension language for Java, an embedded dynamic language (such as Javascript, or Groovy) can be added; most of these can access arbitrary java objects and methods.

Categories