This question already has answers here:
Java Pass Method as Parameter
(17 answers)
Closed 8 years ago.
I'm trying to write a function, so I can pass a function as a parameter, such as
public class HashFunction {
private Function f;
public HashFunction(Function f) {
this.f=f;
}
public Integer hash(String s){
return f(s);
}
}
So I can write code like
new HashFunction(function(String s){ return s.charAt(0)+0; });
Like in javascript.
How can I do this?
Unlike many other modern languages, currently java doesn't syntactically support "floating chunks of code" (known as closures).
However, the concept may be achieved through the use of anonymous classes, which are "on the fly" implementation declarations that typically implement an interface, but can also extend a class.
Here's how you would code your example in java:
public interface Hasher {
int getHash(String s);
}
public class HashFunction {
private Hasher f;
public HashFunction(Hasher f) {
this.f=f;
}
public Integer hash(String s){
return f(s);
}
}
then to use:
new HashFunction(new Hasher() {
public int getHash(String s) {return s.charAt(0)+0;}
});
Passing functions as parameters is not possible in Java, unless they added it in a recent language change.
The Java pattern is to use so-called anonymous classes, which implement a member method which has the desired behavior.
For example, see:
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm
or
How are Anonymous (inner) classes used in Java?
I think you can use interface, the same way like Comparable or Comparator interface, or use annotation to mark some functions, and then use reflection to invoke them
Please check this
I can only second the other answers. Basically, it is not possible to pass real references to functions, like in JavaScript or Haskell, where "everything is a function".
However, if you want to have a little bit of "functional"-style programming in your code, take a look at the "Functional Java" library at http://functionaljava.org/
Maybe taking a look at Scala also can be helpful, as it runs in the JVM and is a very mature, upcoming and modern programming language. In Scala, you can pass functions and it would interoperate with your existing Java code, too. (There are functions, functors, monads, list comprehensions, ...)
functions are called methods in java. And you can pass them!!!
But this is advanced java. Use java.lang.reflection.Method to pass a method.
But you will not happy with that technique.
Related
This question already has answers here:
Non-class functions in Java
(4 answers)
Closed 2 years ago.
When declaring methods in Java, do they need to be a part of a class? I am familiar with the idea of a Utility Class:
"Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated. It contains a bunch of related methods, so they can be reused across the application."
However, can one just create a method separate from any class altogether? (I'd assume scope becomes public by default and declaring anything else for scope might result in an error).
If this is not possible, perhaps that would explain the need for Utility Classes, but I wasn't sure as I hadn't thought about this before - I assumed naturally you could make functions separate from any specific class, but I had been looking through various code samples and couldn't find a specific example where this was occurring.
Part of the reason I am asking this is I was reviewing this article (and mentioned in point 2):
https://www.geeksforgeeks.org/lambda-expressions-java-8/
In it, it states: Lambda expressions are added in Java 8 and provide below functionalities.
1) Enable to treat functionality as a method argument, or code as data.
2) A function that can be created without belonging to any class.
3) A lambda expression can be passed around as if it was an object and executed on demand.
Java is a sort of purely class-based programming language. So, Yes, it and everything needs to be a part of a class.
You are right, you can make a Utility class making methods public static in this way methods can be called without instantiating the class.
Answer to question in the comment:
Why would someone write Object.method() instead of just method()?
Object class is a standard class in java.lang package. You should not create your class named Object otherwise you will need to specify java.lang.Object everywhere you use java.lang.Object.
Now you probably meant
Why would someone write MyUtilClass.method() instead of just method()?
Suppose you have a class MyUtilClass as follows
public class MyUtilClass {
public static int utilMethodA() {
return 1;
}
public static boolean utilMethodB() {
int value = utilMethodA();
if(value == 1)
return true;
else
return false;
}
}
And suppose you have another class MyClass as
public class MyClass {
public void classMethod() {
int value = MyUtilClass.utilMethodA();
}
}
Here if you see in MyUtilClass, utilMethodB() uses utilMethodA() without writing MyUtilClass.utilMethodA() (however, we could write it that way also). Here we did not need to write it as MyUtilClass.utilMethodA() because compiler can find the utilMethodA() without fully specifying it's class because it is present inside it's own class.
Now, In Myclass's myMethod(), we must specify MyUtilClass.utilMethodA() (without it, it won't work), because the compiler has no way of figuring out that you meant to call utilMethodA() of MyUtilClass. There could be hundreds of classes with a method named utilMethodA(), the compiler has no way of finding out which one of the hundred methods you want to call.
Note:-
Also, you can do static import of MyUtilClass.myMethod() like
import static my.package.name.MyUtilClass.myMethodA()
and then use utilMethodA() inside MyClass without prefixing MyUtilClass (but you already informed compile by static import that you will be using utilMethodA() of MyUtilClass right?)
Looks cool to you? No!
This is rather a bad way because
It makes code looks unobvious. In a large class, it may seem that
method utilMethodA() is a local method defined somewhere in
MyClass.
Also, it can generate ambiguity to the compiler if more than one static import of utilMethodA() is done. As compiler has no way of figuring out which of the two you intend to use.
(Edit) Regarding Lambda Expression
Lambda expression is pretty cool stuff added in Java 8. They are basically a kind of function. They provide you the power to define a function right where they need to be used. For example in this link that you provided, see the example shown below syntax of lambda, there the statement
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(1);
arrL.add(2);
arrL.add(3);
arrL.add(4);
arrL.forEach(n -> { if (n%2 == 0) System.out.println(n); });
Basically, what we are doing here is, we are defining a function, if n is multiple of 2, we print n. We are doing it forEach element of arrL. Did you see, we defined the function to be executed on each element right inside a function call forEach(). That's the beauty of lambda expression.
Now, coming to your question,
So the primary benefit of lambda (besides syntax) is to make it easier to implement functional interfaces (compared to what alternative)?
Yes, sort of. Easy in terms of not creating a separate class implementing the interface and then implementing the abstract method and then calling that implemented method.
This becomes lots of work, especially if you need to call that method only once for example,
Consider the Functional Interface FuncInterface defined as in the link in your question:
interface FuncInterface {
// An abstract function
void abstractFun(int x);
// A non-abstract (or default) function
default void normalFun() {
System.out.println("Hello");
}
}
Now, you want two kind of implementation to your functional interface:
One that provides twice of the passed int x.
Another one that provides square of passed int x.
So, you make two implementations of it:
First FuncInterfaceTwiceImpl
public class FuncInferFaceTwiceImpl implements FuncInterface {
#Override
public void abstractFun(int x) {
System.out.println(2 * x);
}
}
Second, FuncInterfaceSquareImpl as
public class FuncInterfaceSquareImpl implements FuncInterface {
#Override
public void abstractFun(int x) {
System.out.println(x * x);
}
}
Now, you call them as
public class MyClass {
public static void main(String[] args) {
FuncInterface interfaceTwiceObject = new FuncInferFaceTwiceImpl();
interfaceTwiceObject.abstractFun(5);
FuncInterface interfaceSquareObject = new FuncInterfaceSquareImpl();
interfaceSquareObject.abstractFun(5);
}
}
It prints
10
25
Now, what you had to do?
You had to create two separate Classes (in separate new files or
could have made private classes in the same file that of MyClass),
each implementing the abstract method.
Then you instantiated objects of each class and called them
respectively in the main function.
What if this is the only place where you had to call this twice and square thing? You had to make two classes just to use them only once. This effort is too much!!
What if you want to call it without creating new classes and implementing methods in a class?
What if I tell you only provide me the method body, I will do the work for you without you to bother about implementing interface and overriding methods?
Here comes the Lambda magic. Instead of making any impl classes just
head straight towards the main method
Instantiate two objects of FuncInterface providing only method body in Lambda expression.
Call abstract method from objects just like below
public class MyClass {
public static void main(String[] args) {
FuncInterface interfaceTwiceObject = (n) -> System.out.println(2*n);
interfaceTwiceObject.abstractFun(5);
FuncInterface interfaceSquareObject = (n) -> System.out.println(n*n);
interfaceSquareObject.abstractFun(5);
}
}
And boom, the output is
10
25
Just one more time where Lambda saved your day!!
Yes all methods in Java have to be part of a class. You cannot create a method (static or otherwise) which is not associated with a class.
EDIT
Before I answer your question, I will point out that lambda expressions were introduced in Java 8 through the concept of SAM types. In addition, a bit of syntactic sugar was also introduced to facilitate the creation of these types.
When you hear the term "Lambda expression" in Java, you should always remember that they are expressions. Your confusion stems from thinking that lambda expressions evaluate to a pure function not associated with a class or object; well this is simply not the case in Java and I will show you why.
Lambda expressions are not functions
I can now see where your confusion comes from because that article you are reading made a false claim when they say that lambda expression is:
A function that can be created without belonging to any class.
This is simply not true. A lambda expression in Java is not a function. Take the example they give for instance.
interface FuncInterface
{
// An abstract function
void abstractFun(int x);
// A non-abstract (or default) function
default void normalFun()
{
System.out.println("Hello");
}
}
class Test
{
public static void main(String args[])
{
// lambda expression to implement above
// functional interface. This interface
// by default implements abstractFun()
FuncInterface fobj = (int x)->System.out.println(2*x);
// This calls above lambda expression and prints 10.
fobj.abstractFun(5);
}
}
Proof
Now take the comment they have in the main method:
lambda expression to implement above functional interface
From the start they admit that the next line of code implements a functional interface. However functions in Java do not implement interfaces, only classes or other interfaces can do that!
Now, they even go ahead and "call" this function:
This calls above lambda expression and prints 10.
except instead of directly invoking the function (as anyone would if this was really a function), they use the property accessor notation (.) to access the actual method they wanted to call, which means what we have here is not a function, but actually an instance of an anonymous class.
Furthermore, since this object actually contains another method (normalFun), one might ask the question, which one do I use when I want to pass this "function" to another method? This is not a question that is commonly (if ever) asked in the context of lambda functions because there is only one thing to do with a lambda function and that is to call it.
In closing
Java has lambda expressions, not lambda functions.
What makes it a lambda expression is simply the syntactic sugar introduced in Java 8 that uses the () -> { } notation. Unfortunately, many fans of functional programming began associating the term "Lambda function" with objects created using this syntax, and this has led to the confusion you have expressed in your question.
To rehash what I answered previously, all functions in Java are part of a class, and you cannot have a function which is not associated with an object, nor can you create a function outside a class.
HTH
This question already has answers here:
Are getters and setters poor design? Contradictory advice seen [duplicate]
(16 answers)
Closed 4 years ago.
I have been developing in Java specifically over 5 years now.
Now always when I start writing a new class or code, I start with defining the properties of my class. So I will need to hit eclipse generate getter and setter every time to my dissapoint. And that is cleaner code and much more understandable in the end.
But I enjoy thinking abstract and using of OOP and generics.
So there is either an specific reason people need to use Java primitives or we can just create a class like this in Java to always have an getter and setter and still be within the normal use of Java class members :
public class Property<Type> implements Getter<Type>,Setter<Type>{
protected Type value;
public Property() {
}
#Override
public <T extends Type> void set(T value) {
this.value = value;
}
#Override
public Type get() {
return value;
}
public String toString() {
return value.toString();
}
}
You can still use modifiers to limit the access to the variables you define. You will still use the same variable declaration as in:
Class test{
private Property<Number> priv_floatProperty = new Property<Float>();
protected Property<Number> prot_floatProperty = new Property<Float>();
public Property<Number> publ_floatProperty = new Property<Float>();
}
Just wanted to ask this question to see what other people think about this code and writing your classes in this way. I really hope I can get some feedback about this code and the theory of class design in Java,
I think that you should use generics only if necessary.
First, for readability.
Second, you can fastly hit the Java Type Erasure problem (see). So you could encounter lot of problem when comparing classes (and the use of appropriate .equals/.hashcode methods). I have seen some difficult cases where the only solution was to use unreadable, complicated and performance-cost reflections...
As suggested, you can use Lombok to make an abstraction of getters/setters.
This question already has answers here:
Why is method overloading and overriding needed in java? [duplicate]
(2 answers)
Closed 4 years ago.
I asked on SE how to make a function that accepts different kinds of variables. People have told me to "overload".
My question: how do I use overloading to make a function that will accept multiple data types (int bool string) as it's input?
Also, what are the advantages and disadvantages of overloading? Is it related to "overloading my computer"?
Overloading is a concept that doesn't hurt your computer but sometimes it makes your head hurt. Not really. Overloading is just writing multiple implementations of a method with the same name but different parameter types. It requires the programmer to write code like this. Notice the return types are the same.
public int SomeMethod(int someValue)
{ //one implementation for ints }
public int SomeMethod(String someValue)
{ //another implementation for strings}
Which method is invoked depends on on the argument type. The method invoked here is the one for integer arguments:
int result = SomeMethod(5);
Another way of doing this is using Generic Methods. This is a little advanced for the question asked, but it might be what you're looking for. The Oracle Java Documentation is a good place to start.
Try looking into generic types: https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html
Overloading is a concept. It will not affect your computer or your code. It is simply the fact of declaring multiple methods in your class with the same name but different arguments.
For example:
private int doSomething(int anInteger) {
// do something with an integer
}
private int doSomething(float aFloat) {
// do something with a float
}
Doing this will allow you to use the same method name on different parameter types, but have different method implementation.
public void myFunction(String s){ ... }
public void myFunction(int i){ ... }
public void myFunction(bool b){ ... }
Really you should be able to google "java overloading" or something instead of posting on here for this. Googling is a top developer skill. Read the documentation, or your textbook or something.
Is there anyway to override a method at run time? Even if it requires dynamically creating a subclass from that instance?
With plain Java, no.
With ByteBuddy(preferred), asm, cglib or aspectj, yes.
In plain Java, the thing to do in a situation like that is to create an interface-based proxy that handles the method invocation and delegates to the original object (or not).
You could create an anonymous class that overrides the method and uses the strategy pattern to decide what to do.
If you are looking for dynamic compilation from code, you can follow these instructions
As others said, no, you can't override a method at runtime. However, starting with Java 8 you can take the functional approach. Function is a functional interface that allows you to treat functions as reference types. This means that you can create several ones and switch between them (dynamically) a-la strategy pattern.
Let's look at an example:
public class Example {
Function<Integer, Integer> calculateFuntion;
public Example() {
calculateFuntion = input -> input + 1;
System.out.println(calculate(10));
// all sorts of things happen
calculateFuntion = input -> input - 1;
System.out.println(calculate(10));
}
public int calculate(int input) {
return calculateFuntion.apply(input);
}
public static void main(String[] args) {
new Example();
}
}
Output:
11
9
I don't know under what circumstances and design you intend to override, but the point is that you replace the behavior of the method, which is what overriding does.
I think it not possible with simple Java.
With reflection and/or cglib probally you can do it.
Look at these links:
http://www.rgagnon.com/javadetails/java-0039.html
http://www.javaworld.com/javaworld/jw-06-2006/jw-0612-dynamic.html
I'm coming from the world of c#.
in C# i am able to use the class dynamic http://msdn.microsoft.com/en-us/library/dd264741.aspx
This allows me to not have to use templated/generic classes but achieve a simliar feel for certian situations.
I'm have been unsuccessfull in internet searchs as unfortunately 'dynamic' and 'java' keywords turn up alot of unrelated infromation on dynamic architectures.
I have dabbled a bit in javaFX and there is a type var which appears to have the same usage as c#'s dynamic. However it doesnt appear to be usable in Java.
thanks,
stephanie
Java doesn't support dynamic typing, but you can simulate something like that using dynamic proxy in Java. First you'll need to declare an interface with operations you want to invoke on your objects:
public interface MyOps {
void foo();
void boo();
}
Then create Proxy for dynamic invocation on myObjectInstance:
MyOps p = (MyOps) Proxy.newProxyInstance(getClass().getClassLoader(), //
new Class<?>[] { MyOps.class }, //
new MyHandler(myObject));
p.foo();
p.boo();
where MyHandler is declared like this:
public class MyHandler implements InvocationHandler {
private final Object o;
public MyHandler(Object o) {
this.o = o;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Method method = o.getClass().getMethod(m.getName(), m.getParameterTypes());
return method.invoke(o, args);
}
}
so, if myObject has methods foo() and boo(), they will be invoked, or else, you'll get a RuntimeException.
There is also number of languages that can run in JVM support dynamic typing, e.g. Scala, Groovy, JRuby, BeanShell, JavaScript/Rhino and many others. There is some JVM changes are coming in Java 7 to support a native dynamic dispatch, so these languages could perform much better, but such feature won't be directly exposed in statically typed Java language.
There is nothing like that in Java
There's nothing equivalent in Java. The closest thing you could do is declare a variable of type Object but then you have to cast that variable to whatever you're expecting in order to invoke any method on it that's not implemented by Object (or use reflection but that's sloooow).
Java is a strongly typed language. I think for the next version there will be some dynamic typing, to allow for closures, but that's next year or more probably 2012.
In Groovy you can just use "def" to declare a variable without a type, and the type will be resolved at runtime. And you can compile the Groovy code to Java bytecode...
You can also include Scala code, which does not require explicit type declarations. Scala produces Java byte code. I haven't used C#, so I'm afraid I can't take this comment to the point of responding directly to the question. Maybe someone else can add to it.