I want to create a method that takes print method reference as argument. Is there any way to create a method like below?
public static void main(String [] args) {
runFunction(System.out::print);
}
public static void runFunction(MethodRef methodRef){
methodRef("test");
}
EDIT:
I have created a functional interface like;
public interface Generatable<T> {
void generate(T t);
}
And I updated my runFunction as;
public static void acceptFunction(Generatable generatable){
generatable.generate("test");
}
this method works perfectly but I still don't get how it works. I mean how it calls print method when I call generate("test").
Yes, like Prashant said.
But if you use a functional interface you better add a generic type like that:
public static void runFunction(Consumer<String> consumer){
consumer.accept("test");
}
For more functional interfaces you can take a look at https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
Yes, you can use a Consumer as:
public static void runFunction(Consumer consumer){
consumer.accept("test");
}
Side note: Functional programming is only supported with Java 8 +. So if you are using any version of Java below 8, this will not work and there is no simple way of fulfilling your requirement.
Related
I got into programming a bit obliquely with Bukkit and thus didn't learn some things properly. But since I've been doing real stuff for a while now I wanted to ask how to deal with static.
I know that you should avoid static as most as possible.
Should you then call external functions like this?
//Another Class
public void exampleMethodInAnotherClass() {
system.out.prinln("Hi :D");
}
//Main
public static void main(String[] args) {
new AnotherClass().exampleMethodInAnotherClass();
}
//OR
public static void exampleMethodInAnotherClass() {
system.out.println("Hi :D");
}
public static void main(String[] args) {
AnotherClass.exampleMethodInAnotherClass();
}
Now it's about the type of function that you use if the function is too much used in your code like System.out.println then make it static *(static function are mostly common in maths and helper classes).
OH the static keyword , My most hero in the programming!
I know that you should avoid static as most as possible.
no that's not true in the most cases the programmer that are student or new in the programming think it's best Idea that we have use static key but it's important to know the why we use static.
after you use static key the variable imidediately going to memory and you can accsess it directly by calling the refrence! and it's the package and class with the variable name but the static method is in the memory and if you change it from some where in your code the data change , see some example :
public class Test {
static String MESSAGE= "";
public static setMessage(String message){
MESSAGE = message;
}
public static void showMessage(){
System.out.println(MESSAGE);
}
}
----------------
Calling from another class
public static void showMessage(){
System.out.println(Test.MESSAGE);
}
if you run the program and change the message with the showMessage method you can get the message and if you need you can call the MESSAGE by reference Like ClassName.MESSAGE or create object from your class with new Keyword but your MESSAGE variable is static and in your memory after running your code so the use new keyword to call it not nesssasery and you can call it directly ! remember using the static variable in mini or script cases or test is good idea but if you create Enterprise project using static method or variable without knowledge about it it's bad idea! because , I most use static keyword for method or variable I need always return same result or work straight work I need! like show the time , convert date or etc... but don't use for changing the data The example I share it's good ref for know the problem.
Good ref for know the static internal work it's here
I couldn't think of a good way to name this. Basically I'm have a program where I want to have a default "pattern" almost I guess of how something should function. But I wanted to allow the use to create their own implementation (This is like an API) of the class and use that as a parameter instead, with the functionality inside. Is this the most efficient way to do it? If you don't understand that bad description here is an example.
public class SimpleStyle extends AbstractStyle {
public void personalizedImplementation() {
// manipulate the program this way
}
}
Then in the method
public static void do(Class<? extends AbstractSyle> style) {
// Use reflection in herre to get the implementation and do it
}
Is there a better and more efficient way to do something like this
You should not use reflection for this task if you can avoid it. It is less readable and more error-prone than well designed interfaces.
The basic solution (I’m not sure whether you already considered it) is to simply pass instances of AbstractStyle to your method:
public static void doSomething(AbstractStyle style) {
style.personalizedImplementation();
}
public static void main(String[] args) {
do(new SimpleStyle());
}
If you cannot use this approach – this depends on the specific use case – you could define an additional interface that handles the creation of the AbstractStyle instance:
public interface StyleFactory {
AbstractStyle createStyle();
}
public class SimpleStyleFactory implements StyleFactory {
#Override
public SimpleStyle createStyle() {
return new SimpleStyle(/* ... */);
}
}
public static void doSomething(StyleFactory styleFactory) {
AbstractStyle style = styleFactory.createStyle();
style.personalizedImplementation();
}
public static void main(String[] args) {
do(new SimpleStyleFactory());
}
Note: do is a Java keyword, so it can’t be used as an identifier. I used doSomething instead.
I come from a Python background and in Python you can pass in the type of an object as a parameter. But in Java you cannot do this, any tips on how to get something like this working?
private void function(Type TypeGoesHere)
Stock s = new TypeGoesHere();
s.analyze();
}
Java does not support Python’s way of referencing functions and classes. To achieve this behaviour, you have to use two advanced techniques: generics and reflection. Explaining these concepts is beyond the scope of a SO answer. You should read a Java guide to learn about them.
Yet here is an example how this would look like, assuming that the given class has a no-argument constructor:
public <T extends Stock> void analyzeNewStock(Class<T> clazz) throws Exception {
Stock s = clazz.newInstance();
s.analyze();
}
Then call this function with analyzeNewStock(MyStock.class).
As this is a rather complicated and error-prone approach, you’d rather define an interface that creates Stock instances:
public interface StockProvider {
Stock createStock(String value);
}
public class MyStockProvider implements StockProvider {
private final String valueTwo;
public MyStockProvider(String valueTwo) {
this.valueTwo = valueTwo;
}
#Override
public Stock createStock(String valueOne) {
return new MyStock(valueOne, valueTwo);
}
}
public class MyOtherClass {
public void analyzeNewStock(StockProvider provider) {
provider.createStock("Hi!").analyze();
}
public static void main(String[] args) {
analyzeNewStock(new MyStockProvider("Hey!"));
}
}
In Java you can pass a Class. You can do it like this:
private void function(Class c)
This is not very common procatice though. You can probably get wha you need by looking into Strategy pattern, or proper use of Object Oriented Programming (polymorphism).
If you are looking for a way to build some objects, look into Factory pattern.
If you want to create a generic class- look into this detailed answer: https://stackoverflow.com/a/1090488/1611957
You could use generics. For example:
private <T> void function(Class<T> clazz) {
try{
T t = clazz.newInstance();
//more code here
}catch(InstantiationException | IllegalAccessException ex){
ex.printStackTrace();
}
}
The Class<T> clazz shows what type to instantiate. The try/catch is just to prevent errors from stopping your code. The same idea is expanded in this SO post. More info here.
However, I'm not really sure why you would want to do this. There should easily be a workaround using a simple interface. Since you already know that you want an object with type Stock, you could pass an implementation of the interface. For example:
//interface to implement
public interface Stock {
public void analyze();
}
//rewrite of function
private void function(Stock s){
s.analyze();
}
And using two ways to call function:
//first way
public class XYZ implements Stock{
public void analyze(){
//some code here
}
}
//calling the function
function(new XYZ());
//second way
function(new Stock(){
public void analyze(){
//your code here
}
});
My question is more towards the design pattern to use for my implementation. I have the code written as follows -
X-Service.java
handler.setListeners(new HttpResponseHandler.conListers() {
#Override
public void success() {
}
});
HttpResponseHandler
protected conListers conListener;
public interface conListers {
public void success();
}
public void conListers(conListers listener) {
this.conListers = listener;
}
So now my problem is I can use this technique If I had just one type of success function. To be more clear I have multiple services where success method have different signature like --
public void success(String x);
public void success(HashMap y, Integer z);
I do not want to put all the methods in the interface, as I will have to implement them in all the services. I need a way in which I can just implement the success method I want.
You could define the interface using a generic type declaration:
public interface conListers<E> {
public void success(E value);
}
Alternatively, if you need a variable number of arguments of the same type then you can use:
public interface conListers<E> {
public void success(E... value);
}
If you need a fixed number of arguments then you can just test the length of the value argument in the definition of success() in the implementing class.
However, I can't think of any pattern you can use to allow success() to take a variably fixed number of different typed arguments unless you use Object but that then brings its own issues (like having to type check all the arguments within the implementing class):
public interface conListers {
public void success(Object... value);
}
You can use the command pattern in this scenario, basically the conListener will be your command. You'll have as many conListeners implementations as your services.
Example:
public class conListenersA implements conListener{
protected Service serviceA;
public void success(){
serviceA.success(arg1);//the method has arguments
}
}
public class conListenersB implements conListener{
protected Service serviceB;
public void success(){
serviceB.success(arg1,arg2);//the method has 2 arguments
}
}
The advantage is that whenever you need to execute a conListener you call will be "uniform", as simple as conListener.success()
You can try with most general Java class Object as a parameter and use varargs:
public interface conListers {
public void success(Object... arguments);
}
Inside implementation you'll have to figure out object types and the number of arguments, but you'll have a clean interface for your functions.
Another approach is to define a class that holds all of your arguments that you are planning to send on a success, and then inside implemented success methods get parameters that you really need.
I am a Software Engineer in Test, and I am trying to write code that can replace production side method so that test can execute those instead. Basically, I do not want to modify production code for testability.
Here is a simple scenario:
public class Foo {
public static void foo() {
printA();
}
public static void printA() {
System.out.println("A");
}
public static void printB() {
System.out.println("B");
}
}
public class Foobar {
public Foobar() {
}
public void test() {
Foo.foo();
}
public static void main(String[] args) {
//Try changing the method here
new Foobar().test();
}
}
As you can see, when the main executes, it will print "A" since it calls the method printA on static method foo(). Now on runtime, is there a way I can inject or modify such that foo will call printB instead of printA?
Thank you for all the help!
Look at AspectJ.
It provides advices, which can be used to execute some code around a method (before and after its execution), including bypassing the call to original method altogether and returning some arbirary value
If you're just doing this for testing out classes, you could use a mocking framework to mock the classes on the server. I like Mockito.
You can do it yourself using the java reflection api, or you can you use a tool like PowerMock.