<p>Does the Java language have delegate features, similar to how C# has support for delegates?</p>

[{'answer_id': 44916, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://web.archive.org/web/20110628230222/http://java.sun.com/docs/white/delegates.html" rel="noreferrer">Short story: \xad\xad\xad\xad\xad\xad\xad\xad\xad\xad\xad\xad\xad\xad\xad\xad\xad\xad\xadno</a>.</p>\n<blockquote>\n<h1>Introduction</h1>\n<p>The newest version of the Microsoft Visual J++ development environment\nsupports a language construct called <em>delegates</em> or <em>bound method\nreferences</em>. This construct, and the new keywords <code>delegate</code> and\n<code>multicast</code> introduced to support it, are not a part of the Java<sup>TM</sup>\nprogramming language, which is specified by the <a href="http://web.archive.org/web/20110628230222/http://java.sun.com/docs/books/jls/second_edition/html/j.title.doc.html" rel="noreferrer">Java Language\nSpecification</a> and amended by the <a href="http://web.archive.org/web/20110628230222/http://java.sun.com/products/archive/jdk/1.1/index.html" rel="noreferrer">Inner Classes Specification</a> included\nin the <a href="http://web.archive.org/web/20110628230222/http://java.sun.com/products/archive/jdk/1.1/index.html" rel="noreferrer">documentation for the JDKTM 1.1 software</a>.</p>\n<p>It is unlikely that the Java programming language will ever include\nthis construct. Sun already carefully considered adopting it in 1996,\nto the extent of building and discarding working prototypes. Our\nconclusion was that bound method references are unnecessary and\ndetrimental to the language. This decision was made in consultation\nwith Borland International, who had previous experience with bound\nmethod references in Delphi Object Pascal.</p>\n<p>We believe bound method references are <em>unnecessary</em> because another\ndesign alternative, <em>inner classes</em>, provides equal or superior\nfunctionality. In particular, inner classes fully support the\nrequirements of user-interface event handling, and have been used to\nimplement a user-interface API at least as comprehensive as the\nWindows Foundation Classes.</p>\n<p>We believe bound method references are <em>harmful</em> because they detract\nfrom the simplicity of the Java programming language and the\npervasively object-oriented character of the APIs. Bound method\nreferences also introduce irregularity into the language syntax and\nscoping rules. Finally, they dilute the investment in VM technologies\nbecause VMs are required to handle additional and disparate types of\nreferences and method linkage efficiently.</p>\n</blockquote>\n'}, {'answer_id': 44928, 'author': 'Matt Sheppard', 'author_id': 797, 'author_profile': 'https://Stackoverflow.com/users/797', 'pm_score': 8, 'selected': True, 'text': '<p>Not really, no.</p>\n<p>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).</p>\n<p>You might also find this article interesting / useful : <a href="https://web.archive.org/web/20210225165533/https://www.blueskyprojects.com/print-design/" rel="nofollow noreferrer">A Java Programmer Looks at C# Delegates (@blueskyprojects.com)</a></p>\n'}, {'answer_id': 45009, 'author': 'John Meagher', 'author_id': 3535, 'author_profile': 'https://Stackoverflow.com/users/3535', 'pm_score': 0, 'selected': False, 'text': '<p>While it is nowhere nearly as clean, but you could implement something like C# delegates using a Java <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Proxy.html" rel="nofollow noreferrer">Proxy</a>.  </p>\n'}, {'answer_id': 2075606, 'author': 'Lawrence Dol', 'author_id': 8946, 'author_profile': 'https://Stackoverflow.com/users/8946', 'pm_score': 2, 'selected': False, 'text': '<p>I have implemented callback/delegate support in Java using reflection.  Details and working source are <a href="http://www.softwaremonkey.org/Code/Callback" rel="nofollow noreferrer">available on my website</a>.</p>\n\n<h2>How It Works</h2>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>static private final Method             COUNT =Callback.getMethod(Xxx.class,"callback_count",true,File.class,File.class);\n\n...\n\nIoUtil.processDirectory(root,new Callback(this,COUNT),selector);\n\n...\n\nprivate void callback_count(File dir, File fil) {\n    if(fil!=null) {                                                                             // file is null for processing a directory\n        fileTotal++;\n        if(fil.length()&gt;fileSizeLimit) {\n            throw new Abort("Failed","File size exceeds maximum of "+TextUtil.formatNumber(fileSizeLimit)+" bytes: "+fil);\n            }\n        }\n    progress("Counting",dir,fileTotal);\n    }\n</code></pre>\n\n<p>IoUtil.processDirectory():</p>\n\n<pre><code>/**\n * Process a directory using callbacks.  To interrupt, the callback must throw an (unchecked) exception.\n * Subdirectories are processed only if the selector is null or selects the directories, and are done\n * after the files in any given directory.  When the callback is invoked for a directory, the file\n * argument is null;\n * &lt;p&gt;\n * The callback signature is:\n * &lt;pre&gt;    void callback(File dir, File ent);&lt;/pre&gt;\n * &lt;p&gt;\n * @return          The number of files processed.\n */\nstatic public int processDirectory(File dir, Callback cbk, FileSelector sel) {\n    return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);\n    }\n\nstatic private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {\n    int                                 cnt=0;\n\n    if(!dir.isDirectory()) {\n        if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }\n        }\n    else {\n        cbk.invoke(dir,(Object[])null);\n\n        File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));\n        if(lst!=null) {\n            for(int xa=0; xa&lt;lst.length; xa++) {\n                File ent=lst[xa];\n                if(!ent.isDirectory()) {\n                    cbk.invoke(dir,ent);\n                    lst[xa]=null;\n                    cnt++;\n                    }\n                }\n            for(int xa=0; xa&lt;lst.length; xa++) {\n                File ent=lst[xa];\n                if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }\n                }\n            }\n        }\n    return cnt;\n    }\n</code></pre>\n\n<p>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 <em>for</em> 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.</p>\n\n<p>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".</p>\n'}, {'answer_id': 3953773, 'author': 'Michael', 'author_id': 478586, 'author_profile': 'https://Stackoverflow.com/users/478586', 'pm_score': 4, 'selected': False, 'text': '<p>Have you read <a href="http://www.javawebdevelop.com/2262189/" rel="noreferrer">this</a> :</p>\n\n<blockquote>\n  <p>Delegates are a useful construct in event-based systems. Essentially\n  Delegates are objects that encode a method dispatch on a specified\n  object. This document shows how java inner classes provide a more\n  generic solution to such problems.</p>\n  \n  <p>What is a Delegate? Really it is very similar to a pointer to member\n  function as used in C++. But a delegate contains the target object\n  alongwith the method to be invoked. Ideally it would be nice to be\n  able to say:</p>\n  \n  <p>obj.registerHandler(ano.methodOne); </p>\n  \n  <p>..and that the method methodOne would be called on ano when some specific event was received.</p>\n  \n  <p>This is what the Delegate structure achieves.</p>\n  \n  <p><strong>Java Inner Classes</strong> </p>\n  \n  <p>It has been argued that Java provides this\n  functionality via anonymous inner classes and thus does not need the additional\n  Delegate construct.</p>\n</blockquote>\n\n<pre><code>obj.registerHandler(new Handler() {\n        public void handleIt(Event ev) {\n            methodOne(ev);\n        }\n      } );\n</code></pre>\n\n<blockquote>\n  <p>At first glance this seems correct but at the same time a nuisance.\n  Because for many event processing examples the simplicity of the\n  Delegates syntax is very attractive.</p>\n  \n  <p><strong>General Handler</strong> </p>\n  \n  <p>However, if event-based programming is used in a more\n  pervasive manner, say, for example, as a part of a general\n  asynchronous programming environment, there is more at stake.</p>\n  \n  <p>In such a general situation, it is not sufficient to include only the\n  target method and target object instance. In general there may be\n  other parameters required, that are determined within the context when\n  the event handler is registered.</p>\n  \n  <p>In this more general situation, the java approach can provide a very\n  elegant solution, particularly when combined with use of final\n  variables:</p>\n</blockquote>\n\n<pre><code>void processState(final T1 p1, final T2 dispatch) { \n  final int a1 = someCalculation();\n\n  m_obj.registerHandler(new Handler() {\n    public void handleIt(Event ev) {\n     dispatch.methodOne(a1, ev, p1);\n    }\n  } );\n}\n</code></pre>\n\n<blockquote>\n  <p><strong>final * final * final</strong> </p>\n  \n  <p>Got your attention?</p>\n  \n  <p>Note that the final variables are accessible from within the anonymous\n  class method definitions. Be sure to study this code carefully to\n  understand the ramifications. This is potentially a very powerful\n  technique. For example, it can be used to good effect when registering\n  handlers in MiniDOM and in more general situations.</p>\n  \n  <p>By contrast, the Delegate construct does not provide a solution for\n  this more general requirement, and as such should be rejected as an\n  idiom on which designs can be based.</p>\n</blockquote>\n'}, {'answer_id': 9232634, 'author': 'Dominic Fox', 'author_id': 995737, 'author_profile': 'https://Stackoverflow.com/users/995737', 'pm_score': 3, 'selected': False, 'text': '<p>No, but they\'re fakeable using proxies and reflection:</p>\n\n<pre><code>  public static class TestClass {\n      public String knockKnock() {\n          return "who\'s there?";\n      }\n  }\n\n  private final TestClass testInstance = new TestClass();\n\n  @Test public void\n  can_delegate_a_single_method_interface_to_an_instance() throws Exception {\n      Delegator&lt;TestClass, Callable&lt;String&gt;&gt; knockKnockDelegator = Delegator.ofMethod("knockKnock")\n                                                                   .of(TestClass.class)\n                                                                   .to(Callable.class);\n      Callable&lt;String&gt; callable = knockKnockDelegator.delegateTo(testInstance);\n      assertThat(callable.call(), is("who\'s there?"));\n  }\n</code></pre>\n\n<p>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.</p>\n\n<p>See the <a href="https://github.com/youdevise/karg" rel="noreferrer">karg code on github</a> for more <a href="https://github.com/youdevise/karg/blob/master/src/test/java/com/timgroup/karg/reflection/DelegatorTest.java" rel="noreferrer">tests</a> and <a href="https://github.com/youdevise/karg/blob/master/src/main/java/com/timgroup/karg/reflection/Delegator.java" rel="noreferrer">implementation</a>.</p>\n'}, {'answer_id': 9870470, 'author': 'Manasvi Sareen', 'author_id': 1113155, 'author_profile': 'https://Stackoverflow.com/users/1113155', 'pm_score': 0, 'selected': False, 'text': '<p>No, but it has similar behavior, internally.</p>\n\n<p>In C# delegates are used to creates a separate entry point and they work much like a function pointer.</p>\n\n<p>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.</p>\n\n<p>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. </p>\n'}, {'answer_id': 10137808, 'author': 'Dave Cousineau', 'author_id': 621316, 'author_profile': 'https://Stackoverflow.com/users/621316', 'pm_score': 6, 'selected': False, 'text': "<p>Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern.</p>\n\n<p>Instead of a line like this declaring a named method signature:</p>\n\n<pre><code>// C#\npublic delegate void SomeFunction();\n</code></pre>\n\n<p>declare an interface:</p>\n\n<pre><code>// Java\npublic interface ISomeBehaviour {\n   void SomeFunction();\n}\n</code></pre>\n\n<p>For concrete implementations of the method, define a class that implements the behaviour:</p>\n\n<pre><code>// Java\npublic class TypeABehaviour implements ISomeBehaviour {\n   public void SomeFunction() {\n      // TypeA behaviour\n   }\n}\n\npublic class TypeBBehaviour implements ISomeBehaviour {\n   public void SomeFunction() {\n      // TypeB behaviour\n   }\n}\n</code></pre>\n\n<p>Then wherever you would have had a <code>SomeFunction</code> delegate in C#, use an <code>ISomeBehaviour</code> reference instead:</p>\n\n<pre><code>// C#\nSomeFunction doSomething = SomeMethod;\ndoSomething();\ndoSomething = SomeOtherMethod;\ndoSomething();\n\n// Java\nISomeBehaviour someBehaviour = new TypeABehaviour();\nsomeBehaviour.SomeFunction();\nsomeBehaviour = new TypeBBehaviour();\nsomeBehaviour.SomeFunction();\n</code></pre>\n\n<p>With anonymous inner classes, you can even avoid declaring separate named classes and almost treat them like real delegate functions.</p>\n\n<pre><code>// Java\npublic void SomeMethod(ISomeBehaviour pSomeBehaviour) {\n   ...\n}\n\n...\n\nSomeMethod(new ISomeBehaviour() { \n   @Override\n   public void SomeFunction() {\n      // your implementation\n   }\n});\n</code></pre>\n\n<p>This should probably only be used when the implementation is very specific to the current context and wouldn't benefit from being reused.</p>\n\n<p>And then of course in Java 8, these do become basically lambda expressions:</p>\n\n<pre><code>// Java 8\nSomeMethod(() -&gt; { /* your implementation */ });\n</code></pre>\n"}, {'answer_id': 13739321, 'author': 'Leve', 'author_id': 1778676, 'author_profile': 'https://Stackoverflow.com/users/1778676', 'pm_score': -1, 'selected': False, 'text': "<p>Java doesn't have delegates and is proud of it :). From what I read here I found in essence 2 ways to fake delegates:\n1. reflection;\n2. inner class</p>\n\n<p>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.</p>\n"}, {'answer_id': 21788518, 'author': 'user3311658', 'author_id': 3311658, 'author_profile': 'https://Stackoverflow.com/users/3311658', 'pm_score': 4, 'selected': False, 'text': '<p>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.\n<a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html">http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html</a></p>\n'}, {'answer_id': 23485571, 'author': 'Khulja Sim Sim', 'author_id': 2359488, 'author_profile': 'https://Stackoverflow.com/users/2359488', 'pm_score': 2, 'selected': False, 'text': '<p>Yes &amp; No, but delegate pattern in Java could be thought of this way. <a href="https://www.youtube.com/watch?v=T568mtL9fys" rel="nofollow noreferrer">This video tutorial</a> is about data exchange between activity - fragments, and it has great essence of delegate sorta pattern using interfaces. </p>\n\n<p><img src="https://i.stack.imgur.com/IkVC8.png" alt="Java Interface"></p>\n'}, {'answer_id': 56787211, 'author': '53c', 'author_id': 10630142, 'author_profile': 'https://Stackoverflow.com/users/10630142', 'pm_score': 2, 'selected': False, 'text': '<p>It doesn\'t have an explicit <code>delegate</code> 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:</p>\n\n<pre><code>private interface SingleFunc {\n    void printMe();\n}\n\npublic static void main(String[] args) {\n    SingleFunc sf = () -&gt; {\n        System.out.println("Hello, I am a simple single func.");\n    };\n    SingleFunc sfComplex = () -&gt; {\n        System.out.println("Hello, I am a COMPLEX single func.");\n    };\n    delegate(sf);\n    delegate(sfComplex);\n}\n\nprivate static void delegate(SingleFunc f) {\n    f.printMe();\n}\n</code></pre>\n\n<p>Every new object of type <code>SingleFunc</code> must implement <code>printMe()</code>, so it is safe to pass it to another method (e.g. <code>delegate(SingleFunc)</code>) to call the <code>printMe()</code> method.</p>\n'}, {'answer_id': 59621577, 'author': 'J.Smile', 'author_id': 8443494, 'author_profile': 'https://Stackoverflow.com/users/8443494', 'pm_score': 0, 'selected': False, 'text': '<p>No, Java doesn\'t have that amazing feature. But you could create it manually using the observer pattern. Here is an example:\n<a href="https://stackoverflow.com/questions/59606165/write-c-sharp-delegate-in-java">Write C# delegate in java</a></p>\n'}, {'answer_id': 62166461, 'author': 'Devanshu', 'author_id': 9133555, 'author_profile': 'https://Stackoverflow.com/users/9133555', 'pm_score': 0, 'selected': False, 'text': '<p>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:</p>\n\n<pre><code>  class Class1 {\n        public void show(String s) { System.out.println(s); }\n    }\n\n    class Class2 {\n        public void display(String s) { System.out.println(s); }\n    }\n\n    // allows static method as well\n    class Class3 {\n        public static void staticDisplay(String s) { System.out.println(s); }\n    }\n\n    public class TestDelegate  {\n        public static final Class[] OUTPUT_ARGS = { String.class };\n        public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);\n\n        public void main(String[] args)  {\n            Delegate[] items = new Delegate[3];\n\n            items[0] = DO_SHOW .build(new Class1(),"show,);\n            items[1] = DO_SHOW.build (new Class2(),"display");\n            items[2] = DO_SHOW.build(Class3.class, "staticDisplay");\n\n            for(int i = 0; i &lt; items.length; i++) {\n                items[i].invoke("Hello World");\n            }\n        }\n    }\n</code></pre>\n'}, {'answer_id': 63777276, 'author': 'Hervian', 'author_id': 6095334, 'author_profile': 'https://Stackoverflow.com/users/6095334', 'pm_score': 1, 'selected': False, 'text': '<p>With <a href="https://github.com/Hervian/safety-mirror" rel="nofollow noreferrer">safety-mirror</a> on the classpath you get something similar to C#\'s delegates and events.</p>\n<p>Examples from the project\'s README:</p>\n<h3>Delegates in Java!</h3>\n<pre><code>  Delegate.With1Param&lt;String, String&gt; greetingsDelegate = new Delegate.With1Param&lt;&gt;();\n  greetingsDelegate.add(str -&gt; &quot;Hello &quot; + str);\n  greetingsDelegate.add(str -&gt; &quot;Goodbye &quot; + str);\n\n  DelegateInvocationResult&lt;String&gt; invocationResult = \n  greetingsDelegate.invokeAndAggregateExceptions(&quot;Sir&quot;);\n\n  invocationResult.getFunctionInvocationResults().forEach(funInvRes -&gt; \n\n  System.out.println(funInvRes.getResult()));\n  //prints: &quot;Hello sir&quot; and &quot;Goodbye Sir&quot;\n</code></pre>\n<h3>Events</h3>\n<pre><code>  //Create a private Delegate. Make sure it is private so only *you* can invoke it.\n  private static Delegate.With0Params&lt;String&gt; trimDelegate = new Delegate.With0Params&lt;&gt;();\n\n  //Create a public Event using the delegate you just created.\n  public static Event.With0Params&lt;String&gt; trimEvent= new Event.With0Params&lt;&gt;(trimDelegate)\n</code></pre>\n<p>See also <a href="https://stackoverflow.com/a/63775875/6095334">this</a> SO answer.</p>\n'}]
['https://Stackoverflow.com/questions/44912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3498/']