I am using a Java framework that provides some kind of visitor pattern for processing elements. There is an abstract super class AbstractProcessor<T> (which I cannot change) that provides a method public abstract void process(T visitedElement).
I then have defined several concrete implementations of such processors and instantiate them by Factory Pattern to then use them via their common supertype. Now, how do I get any type of information out of there? I obviously cannot simply return something, since the abstract process-method is of type void.
My only thought so far would be something like a data-field I can add to the concrete implementation (since I cannot change the abstract super class), so to do smth like this:
public class MyProcessor extends AbstractProcessor<SomeType> {
public String data;
#Override
public void process(SomeType t) {
[do stuff...]
this.data = "some important info";
}
}
But to receive this data from - lets say a list of their common super types that do not posess the data-field - I would have to do some ugly type checking and casting like this:
List<AbstractProcessor> list = getProcessors();
list.forEach(p -> {
someType.processWith(p); //someType accepts AbstractProcessor's and then runs their process-method
if(p instanceOf MyProcessor)
System.out.println( ((MyProcessor)p).data );
}
});
Is there any other way to retrieve some type of data that gets calculated during the process method this way?
I think you have an intrinsically unsolvable problem here. I understand you're saying:
You've written several AbstractProcessor subclasses.
They all do different things and produce different results.
You want to treat them all homogeneously, as instances of AbstractProcessor.
But you can't treat them all as instances of the same class, AbstractProcessor, if they all produce different results. You have to know what type of processor you have in order to interpret the results.
You have two options. The first option is to unify the results. For example, you could have an interface called ResultHandler like this:
interface ResultHandler {
void handleSumResult(int result);
void handleConcatResult(String result);
void handleSomeOtherProcessorResult(Whatever result);
}
Pass in an instance of ResultHandler (either during construction or in a separate handleResult method), then (within each processor) invoke the ResultHandler method appropriate to that processor type. If you have several different processors that generate sums in some way, at least they can all call the same handleSumResult API and you don't have to do instanceof anywhere.
The other strategy is to just abandon your attempt to treat all processors homogeneously. I think this might be the better option. Your code obviously knows what processor it needs to use, so just go ahead and instantiate that one, use it, and collect the results from whatever API you define. If there's some reason why you have to treat the processors homogeneously (e.g., the processor class is specified by the user, maybe in a configuration file), then move that abstraction up one level and instead have the user specify a class that owns the entire process of processing the data and collecting the results. Instead of specifying MyProcessor, the use specifies MySomethingElse, and then MySomethingElse both instantiates MyProcessor and handles the results.
I wouldn't use a field here. Instead: define a suitable interface, like ResultProcessor that has a T getResult() method. And then have all those subclasses that need to produce a result implement that interface.
Sure, you still have to cast, but at least you can use a generic T to be flexible and your clients can call a method instead of doing direct field access.
You can make processors "push" data to a hash map for example, which is passed in or accessible globally.
public class MyProcessor extends AbstractProcessor<SomeType> {
public Map<Object, String> data;
#Override
public void process(SomeType t) {
[do stuff...]
this.data.put(this, "some important info");
}
}
That way the client can have the information which abstract processor added which information, all it needs is access to the map.
I'm looking for something that's similar to implementing the java.lang.AutoCloseable interface, where a compiler warning indicating Resource leak: 'xxxx' is never closed is generated.
The use case for this is in a wrapper around a Synchronized Collection in java. The wrapper has an internal semaphore to prevent concurrent modification of the collection.
It allows atomic operations on the collection, in which case the semaphore is acquired and released internally. It also allows the lock to be acquired externally, providing a unique key with which operations can be executed on the collection. The key must be released at the end of the "transaction".
My goal is to create a compiler warning when the lock is acquired and not released within the same method, to prevent deadlock. An alternative design solution that would prevent this is also acceptable.
It's kind of a fun little problem, so I appreciate any insight into it.
As you said
An alternative design solution that would prevent this is also acceptable.
So here it is: As an alternative design solution, use Functional Programming.
Instead of finding out about the error, why not prevent the error from happening in the first place?
Lacking your source code, I make a few assumptions about your code:
Semaphore is your class (or interface) that provides the semaphore to your SynchronizedCollection.
Semaphore provides two methods obtain() and release().
The problem that you're actually facing is a problem of State resp. Change of State which leads to Temporal Coupling. obtain() and release() must be called in order. You can use elements from Functional Programming as an alternative design.
The Semaphore would currently look like this:
public class Sempahore {
// ...
public void obtain() {
// Lock code
}
public void release() {
// Release code
}
}
The Semaphore user would currently look like this:
semaphore.obtain();
// Code protected by the Sempahore.
semaphore.release();
The solution is to combine obtain() and release() into a single function which takes the code to be protected as its argument. This technique is also known as Passing a Block, or more formally as a higher order function - a function that takes another function as an argument or returns another function.
Java also has function pointers, not directly, but indirectly, via references to interfaces. Since Java 8, an interface that has only one abstract method is even called Functional Interface, and Java 8 provides an optional annotation #FunctionalInterface for that.
So, your class Sempahore could instead look like this:
public class Semaphore {
// ...
private void obtain() {
// Lock code
}
private void release() {
// Release code
}
public <V> void protect(final Callable<V> c) throws Exception {
obtain();
try {
return c.call();
} finally {
release();
}
}
}
And the caller would look like this, in Java 7 and older:
semaphore.protect(new Callable<Object>() {
public Object call() {
// Code protected by the Semaphore.
}
});
In Java 8 and newer, the code could also look like this:
semaphore.protect(() -> {
// Code protected by the Semaphore.
});
Quirks about this solution
There's one aspect about Java which sucks completely in this context: Exception Handling. With functional programming, there is urgent need to fix that, but Oracle didn't. I'm still hoping for Java 9, but that won't help all that broken API like java.util.stream that's already out there in the wild. Java 8 still maintains the handle-or-declare-rule of checked exceptions, but functional programming does not take that into account nicely.
There are a few workarounds for that:
Use Runnable, if you do not need return values.
Use your own Callable interface which declares a type parameter for exceptions.
I bet using Runnable is straight-forward and self-explanatory, therefore I won't elaborate on that.
Using your own version of the Callable interface would look like this:
public interface ProtectedCode<V,E> {
V call() throws E;
}
public class Semaphore {
// ...
private void obtain() {
// Lock code
}
private void release() {
// Release code
}
public <V, E> void protect(final ProtectedCode<V, E> c) throws E {
obtain();
try {
return c.call();
} finally {
release();
}
}
}
Now you don't need to mess around with Exception as long as the limited (because it can reflect only one type, not a type set) type inference for type parameter E leads to reasonable results in the compiler.
If you want to be extraordinarily friendly to your users, you could actually offer three variants of the protect method:
public void protect(final Runnable r)
public <V> V protect(final Callable<V> c) throws Exception
public <V,E> V protect(final ProtectedCode<V,E> c) throws E
In order to create compiler warnings, you will need to extend the Eclipse compiler.
An alternative solution was to create a custom check in a software quality analysis system such as Teamscale or SonarQube. The custom checks perform a static analysis of the code (usually based on the abstract syntax tree enriched with semantic information) and create issues whey they detect dodgy code. The issues are displayed on the user interface of the quality analysis system. Eclipse plugins allow an integration of the systems in Eclipse so that the issues can be listed there as well.
While #Christian Hujer did provide a solid solution, I chose to go another route which has been working out well.
There is a wrapper class "Resource" around the SynchronizedCollection which contains:
A semaphore for locking the collection
A randomly generated ID representing the key to the currently held lock
Methods for performing atomic operations on the collection (They acquire the lock, perform the operation, and immediately release it)
Methods for performing non-atomic operations on the collection (They accept an ID as the key and perform the requested operation if the provided key matches the key currently holding the lock)
The class described above is enough to provide sufficient protection around the collection, but what I wanted was compiler warnings if the lock wasn't released.
To accomplish this, there is a "ResourceManager" which implements java.lang.AutoCloseable
This class:
Is passed a reference to the "Resource" via the constructor
Acquires the lock for the reference in the constructor
Provides an API for calling the non-atomic methods on the "Resource" using the key it acquired during construction
Provides a close() method, overriding java.lang.AutoCloseable, which releases the lock acquired during construction
The resource manager is created wherever multiple operations need to be performed on the Resource and a compiler warning is generated if close() is not called on any particular code path. Additionally, in java 7+, the manager can be created in a try-with-resource block and the lock is automatically released, regardless of what happens in the block.
This might just be a question of personal taste and workflow, but in case it's more than that, I feel I should ask anyway.
In Java, what differences are there between creating an instance via constructor and via a static method (which returns the instance)? For example, take this bit of code from a project I'm working on (written up by hand at time of posting, so some shortcuts and liberties are taken):
Plugin main;
Map<int, int> map;
public Handler(Plugin main) {
this.main = main;
}
public static Handler init(Plugin main) {
Handler handler = new Handler(main);
handler.createMap();
}
public void createMap() {
this.map = Maps.newHashMap();
}
In cases like this, what would the difference be between using
Handler handler = new Handler(this);
and
Handler handler = Handler.init(this);
in the Plugin class, besides the fact that createMap() runs only in the latter because it's not called in the constructor?
To clarify, in this case, Plugin is considered the main class.
I know enough Java syntax to be able to write intermediate-level plugins, but not enough about Java itself to know the difference between these two ways of doing this.
EDIT: For instance, the Maps class that I used to create the Map uses a static factory method (I hope I'm using that term correctly) called using the class instead of an object.
There are both advantages and disadvantages of static factory methods.
Advantages
Descriptive, meaningful names.
When invoked they can decide whether to return a new instance
They can return an object of any subtype of the return type
They reduce the verbosity of creating parameterized type instances
Disadvantages
If you provide only static factory methods, classes without public or protected constructors cannot be subclassed
They are not readily distinguishable from other static methods
Source: Effective Java, Second Ed.
The difference is a static factory method is more flexible. It can have all sorts of ways to return an instance. It can do other side stuff. It can have a more descriptive name. It can be invoked by its simple name (e.g. foo(args)) by static import or inheritance.
The constructor call is more certain - the caller knows exactly what's happening - a new instance of that exact class is created.
I've made some new warning settings in eclipse. With these new settings I'm facing a strange warning. After reading I got to know what it is but couldn't find a way to remove it.
Here is my problem with the sample code
public class Test {
private String testString;
public void performAction() {
new Thread( new Runnable() {
#Override
public void run() {
testString = "initialize"; // **
}
});
}
}
The line with ** gives me a warning in eclipse
Read access to enclosing field Test.testString is emulated by a synthetic accessor method.
Increasing its visibility will improve your performance.
Problem is, I don't want to change the access modifier of testString.
Also, don't want to create a getter for it.
What change should be done?
More descriptive example
public class Synthetic
{
private JButton testButton;
public Synthetic()
{
testButton = new JButton("Run");
testButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
/* Sample code */
if( testButton.getText().equals("Pause") ) {
resetButton(); // **
} else if( testButton.getText().equals("Run") ) {
testButton.setText("Pause"); // **
}
}
}
);
}
public void reset() {
//Some operations
resetButton();
}
private void resetButton() {
testButton.setText("Run");
}
}
Lines with ** gives me the same warning.
What is a "synthetic" method?
Starting from the Method class (and it's parent, Member) we learn that synthetic members are "introduced by the compiler", and that JLS §13.1 will tell us more. It notes:
A construct emitted by a Java compiler must be marked as synthetic if it does not correspond to a construct declared explicitly or implicitly in source code
Since this section is discussing binary compatibility the JVMS is also worth referencing, and JVMS §4.7.8 adds a little more context:
A class member that does not appear in the source code must be marked using a Synthetic attribute, or else it must have its ACC_SYNTHETIC flag set. The only exceptions to this requirement are compiler-generated methods which are not considered implementation artifacts....
The Synthetic attribute was introduced in JDK 1.1 to support nested classes and interfaces.
In other words, "synthetic" methods are an implementation artifact that the Java compiler introduces in order to support language features that the JVM itself does not support.
What's the problem?
You're running into one such case; you're attempting to access a private field of a class from an anonymous inner class. The Java language permits this but the JVM doesn't support it, and so the Java compiler generates a synthetic method that exposes the private field to the inner class. This is safe because the compiler doesn't allow any other classes to call this method, however it does introduce two (small) issues:
Additional methods are being declared. This shouldn't be a problem for the vast majority of use cases, but if you're working in a constrained environment like Android and are generating a lot of these synthetic methods you may run into issues.
Access to this field is done indirectly through the synthetic method, rather than directly. This too shouldn't be a problem except for highly performance-sensitive use cases. If you wouldn't want to use a getter method here for performance reasons, you wouldn't want a synthetic getter method either. This is rarely an issue in practice.
In short, they're really not bad. Unless you have a concrete reason to avoid synthetic methods (i.e. you've determined conclusively they are a bottleneck in your application) you should just let the compiler generate them as it sees fit. Consider turning off the Eclipse warning if it's going to bother you.
What should I do about them?
If you really want to prevent the compiler from generating synthetic methods you have a couple of options:
Option 1: Change the permissions
Package-private or protected fields are accessible to inner classes directly. Especially for something like a Swing application this ought to be fine. But you say you want to avoid this, so on we go.
Option 2: Create a getter
Leave your fields alone, but explicitly create a protected or public getter, and use that instead. This is essentially what the compiler ends up doing for you automatically, but now you have direct control over the method's behavior.
Option 3: Use a local variable and share the reference with both classes
This is more code but it's my personal favorite since you're making the relationship between the inner and outer class explicit.
public Synthetic() {
// Create final local instance - will be reachable by the inner class
final JButton testButton = new JButton("Run");
testButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
/* Sample code */
if( testButton.getText().equals("Pause") ) {
resetButton();
} else if( testButton.getText().equals("Run") ) {
testButton.setText("Pause");
}
}
});
// associate same instance with outer class - this.testButton can be final too
this.testButton = testButton;
}
This isn't always actually what you want to do. For instance if testButton can change to point to a different object later, you'll need to rebuild your ActionListener again (though that's also nicely more explicit, so arguably this is a feature), but I consider it the option that most clearly demonstrates its intent.
Aside on thread-safety
Your example Test class is not thread-safe - testString is being set in a separate Thread but you're not synchronizing on that assignment. Marking testString as volatile would be sufficient to ensure all threads see the update. The Synthetic example doesn't have this problem since testButton is only set in the constructor, but since that's the case it would be advisable to mark testButton as final.
In your second example it is not necessary to access testButton directly; you can access it by retrieving the source of the action event.
For the resetButton() method you can add an argument to pass the object to act upon, if you've done that it is not such a big problem lowering its access restrictions.
Given the context (you assign to the variable once as part of a fairly expensive operation), I don't think you need to do anything.
I think the problem is that you are setting a String on the parent class. This will suffer in performance because the Thread needs to look up to see where that variable is again. I think a cleaner approach is using Callable which returns a String and then do .get() or something that returns the result. After getting the result you can set the data back on to the parent class.
The idea is you want to make sure the Thread only does one thing and only one thing instead of setting variables on other classes. This is a cleaner approach and probably faster because the inner Thread doesn't access anything outside of itself. Which mean less locking. :)
This is one of the rare cases where Java's default visibility (also called "package private") is of use.
public class Test {
/* no private */ String testString;
public void performAction() {
new Thread( new Runnable() {
#Override
public void run() {
testString = "initialize"; // **
}
});
}
}
This will do the following:
testString is now available to all classes in the same package as the outer class (Test).
As inner classes are actually generated as OuterClassPackage.OuterClassName$InnerClassName, they also reside in the same package. They can therefore access this field directly.
In contrast to making this field protected, the default visibility will not make this field available to subclasses (except when they are in the same package of course). You therefore don't pollute your API for external users.
When using private, javac will instead generate a synthetic accessor, which itself is just a getter method with Java's default visibility as well. So it basically does the same thing, except with a minimal overhead of an additional method.
Does the Java language have delegate features, similar to how C# has support for delegates?
Not really, no.
You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class).
You might also find this article interesting / useful : A Java Programmer Looks at C# Delegates (#blueskyprojects.com)
Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.
Instead of a line like this declaring a named method signature:
// C#
public delegate void SomeFunction();
declare an interface:
// Java
public interface ISomeBehaviour {
void SomeFunction();
}
For concrete implementations of the method, define a class that implements the behaviour:
// Java
public class TypeABehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeA behaviour
}
}
public class TypeBBehaviour implements ISomeBehaviour {
public void SomeFunction() {
// TypeB behaviour
}
}
Then wherever you would have had a SomeFunction delegate in C#, use an ISomeBehaviour reference instead:
// C#
SomeFunction doSomething = SomeMethod;
doSomething();
doSomething = SomeOtherMethod;
doSomething();
// Java
ISomeBehaviour someBehaviour = new TypeABehaviour();
someBehaviour.SomeFunction();
someBehaviour = new TypeBBehaviour();
someBehaviour.SomeFunction();
With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.
// Java
public void SomeMethod(ISomeBehaviour pSomeBehaviour) {
...
}
...
SomeMethod(new ISomeBehaviour() {
#Override
public void SomeFunction() {
// your implementation
}
});
This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.
And then of course in Java 8, these do become basically lambda expressions:
// Java 8
SomeMethod(() -> { /* your implementation */ });
Short story: no.
Introduction
The newest version of the Microsoft Visual J++ development environment
supports a language construct called delegates or bound method
references. This construct, and the new keywords delegate and
multicast introduced to support it, are not a part of the JavaTM
programming language, which is specified by the Java Language
Specification and amended by the Inner Classes Specification included
in the documentation for the JDKTM 1.1 software.
It is unlikely that the Java programming language will ever include
this construct. Sun already carefully considered adopting it in 1996,
to the extent of building and discarding working prototypes. Our
conclusion was that bound method references are unnecessary and
detrimental to the language. This decision was made in consultation
with Borland International, who had previous experience with bound
method references in Delphi Object Pascal.
We believe bound method references are unnecessary because another
design alternative, inner classes, provides equal or superior
functionality. In particular, inner classes fully support the
requirements of user-interface event handling, and have been used to
implement a user-interface API at least as comprehensive as the
Windows Foundation Classes.
We believe bound method references are harmful because they detract
from the simplicity of the Java programming language and the
pervasively object-oriented character of the APIs. Bound method
references also introduce irregularity into the language syntax and
scoping rules. Finally, they dilute the investment in VM technologies
because VMs are required to handle additional and disparate types of
references and method linkage efficiently.
Have you read this :
Delegates are a useful construct in event-based systems. Essentially
Delegates are objects that encode a method dispatch on a specified
object. This document shows how java inner classes provide a more
generic solution to such problems.
What is a Delegate? Really it is very similar to a pointer to member
function as used in C++. But a delegate contains the target object
alongwith the method to be invoked. Ideally it would be nice to be
able to say:
obj.registerHandler(ano.methodOne);
..and that the method methodOne would be called on ano when some specific event was received.
This is what the Delegate structure achieves.
Java Inner Classes
It has been argued that Java provides this
functionality via anonymous inner classes and thus does not need the additional
Delegate construct.
obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
methodOne(ev);
}
} );
At first glance this seems correct but at the same time a nuisance.
Because for many event processing examples the simplicity of the
Delegates syntax is very attractive.
General Handler
However, if event-based programming is used in a more
pervasive manner, say, for example, as a part of a general
asynchronous programming environment, there is more at stake.
In such a general situation, it is not sufficient to include only the
target method and target object instance. In general there may be
other parameters required, that are determined within the context when
the event handler is registered.
In this more general situation, the java approach can provide a very
elegant solution, particularly when combined with use of final
variables:
void processState(final T1 p1, final T2 dispatch) {
final int a1 = someCalculation();
m_obj.registerHandler(new Handler() {
public void handleIt(Event ev) {
dispatch.methodOne(a1, ev, p1);
}
} );
}
final * final * final
Got your attention?
Note that the final variables are accessible from within the anonymous
class method definitions. Be sure to study this code carefully to
understand the ramifications. This is potentially a very powerful
technique. For example, it can be used to good effect when registering
handlers in MiniDOM and in more general situations.
By contrast, the Delegate construct does not provide a solution for
this more general requirement, and as such should be rejected as an
idiom on which designs can be based.
I know this post is old, but Java 8 has added lambdas, and the concept of a functional interface, which is any interface with only one method. Together these offer similar functionality to C# delegates. See here for more info, or just google Java Lambdas.
http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html
No, but they're fakeable using proxies and reflection:
public static class TestClass {
public String knockKnock() {
return "who's there?";
}
}
private final TestClass testInstance = new TestClass();
#Test public void
can_delegate_a_single_method_interface_to_an_instance() throws Exception {
Delegator<TestClass, Callable<String>> knockKnockDelegator = Delegator.ofMethod("knockKnock")
.of(TestClass.class)
.to(Callable.class);
Callable<String> callable = knockKnockDelegator.delegateTo(testInstance);
assertThat(callable.call(), is("who's there?"));
}
The nice thing about this idiom is that you can verify that the delegated-to method exists, and has the required signature, at the point where you create the delegator (although not at compile-time, unfortunately, although a FindBugs plug-in might help here), then use it safely to delegate to various instances.
See the karg code on github for more tests and implementation.
Yes & No, but delegate pattern in Java could be thought of this way. This video tutorial is about data exchange between activity - fragments, and it has great essence of delegate sorta pattern using interfaces.
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
There is a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array does not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to its inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
What follows is an example using a callback to process the files in a directory tree. This is an initial validation pass which just counts the files to process and ensure none exceed a predetermined maximum size. In this case we just create the callback inline with the API invocation. However, we reflect the target method out as a static value so that the reflection is not done every time.
static private final Method COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class);
...
IoUtil.processDirectory(root,new Callback(this,COUNT),selector);
...
private void callback_count(File dir, File fil) {
if(fil!=null) { // file is null for processing a directory
fileTotal++;
if(fil.length()>fileSizeLimit) {
throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil);
}
}
progress("Counting",dir,fileTotal);
}
IoUtil.processDirectory():
/**
* Process a directory using callbacks. To interrupt, the callback must throw an (unchecked) exception.
* Subdirectories are processed only if the selector is null or selects the directories, and are done
* after the files in any given directory. When the callback is invoked for a directory, the file
* argument is null;
* <p>
* The callback signature is:
* <pre> void callback(File dir, File ent);</pre>
* <p>
* #return The number of files processed.
*/
static public int processDirectory(File dir, Callback cbk, FileSelector sel) {
return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);
}
static private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {
int cnt=0;
if(!dir.isDirectory()) {
if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }
}
else {
cbk.invoke(dir,(Object[])null);
File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));
if(lst!=null) {
for(int xa=0; xa<lst.length; xa++) {
File ent=lst[xa];
if(!ent.isDirectory()) {
cbk.invoke(dir,ent);
lst[xa]=null;
cnt++;
}
}
for(int xa=0; xa<lst.length; xa++) {
File ent=lst[xa];
if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }
}
}
}
return cnt;
}
This example illustrates the beauty of this approach - the application specific logic is abstracted into the callback, and the drudgery of recursively walking a directory tree is tucked nicely away in a completely reusable static utility method. And we don't have to repeatedly pay the price of defining and implementing an interface for every new use. Of course, the argument for an interface is that it is far more explicit about what to implement (it's enforced, not simply documented) - but in practice I have not found it to be a problem to get the callback definition right.
Defining and implementing an interface is not really so bad (unless you're distributing applets, as I am, where avoiding creating extra classes actually matters), but where this really shines is when you have multiple callbacks in a single class. Not only is being forced to push them each into a separate inner class added overhead in the deployed application, but it's downright tedious to program and all that boiler-plate code is really just "noise".
It doesn't have an explicit delegate keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:
private interface SingleFunc {
void printMe();
}
public static void main(String[] args) {
SingleFunc sf = () -> {
System.out.println("Hello, I am a simple single func.");
};
SingleFunc sfComplex = () -> {
System.out.println("Hello, I am a COMPLEX single func.");
};
delegate(sf);
delegate(sfComplex);
}
private static void delegate(SingleFunc f) {
f.printMe();
}
Every new object of type SingleFunc must implement printMe(), so it is safe to pass it to another method (e.g. delegate(SingleFunc)) to call the printMe() method.
With safety-mirror on the classpath you get something similar to C#'s delegates and events.
Examples from the project's README:
Delegates in Java!
Delegate.With1Param<String, String> greetingsDelegate = new Delegate.With1Param<>();
greetingsDelegate.add(str -> "Hello " + str);
greetingsDelegate.add(str -> "Goodbye " + str);
DelegateInvocationResult<String> invocationResult =
greetingsDelegate.invokeAndAggregateExceptions("Sir");
invocationResult.getFunctionInvocationResults().forEach(funInvRes ->
System.out.println(funInvRes.getResult()));
//prints: "Hello sir" and "Goodbye Sir"
Events
//Create a private Delegate. Make sure it is private so only *you* can invoke it.
private static Delegate.With0Params<String> trimDelegate = new Delegate.With0Params<>();
//Create a public Event using the delegate you just created.
public static Event.With0Params<String> trimEvent= new Event.With0Params<>(trimDelegate)
See also this SO answer.
While it is nowhere nearly as clean, but you could implement something like C# delegates using a Java Proxy.
No, but it has similar behavior, internally.
In C# delegates are used to creates a separate entry point and they work much like a function pointer.
In java there is no thing as function pointer (on a upper look) but internally Java needs to do the same thing in order to achieve these objectives.
For example, creating threads in Java requires a class extending Thread or implementing Runnable, because a class object variable can be used a memory location pointer.
No, Java doesn't have that amazing feature. But you could create it manually using the observer pattern. Here is an example:
Write C# delegate in java
The code described offers many of the advantages of C# delegates. Methods, either static or dynamic, can be treated in a uniform manner. The complexity in calling methods through reflection is reduced and the code is reusable, in the sense of requiring no additional classes in the user code. Note we are calling an alternate convenience version of invoke, where a method with one parameter can be called without creating an object array.Java code below:
class Class1 {
public void show(String s) { System.out.println(s); }
}
class Class2 {
public void display(String s) { System.out.println(s); }
}
// allows static method as well
class Class3 {
public static void staticDisplay(String s) { System.out.println(s); }
}
public class TestDelegate {
public static final Class[] OUTPUT_ARGS = { String.class };
public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);
public void main(String[] args) {
Delegate[] items = new Delegate[3];
items[0] = DO_SHOW .build(new Class1(),"show,);
items[1] = DO_SHOW.build (new Class2(),"display");
items[2] = DO_SHOW.build(Class3.class, "staticDisplay");
for(int i = 0; i < items.length; i++) {
items[i].invoke("Hello World");
}
}
}
Java doesn't have delegates and is proud of it :). From what I read here I found in essence 2 ways to fake delegates:
1. reflection;
2. inner class
Reflections are slooooow! Inner class does not cover the simplest use-case: sort function. Do not want to go into details, but the solution with inner class basically is to create a wrapper class for an array of integers to be sorted in ascending order and an class for an array of integers to be sorted in descending order.