Java helper for class

@Helper

With a little help from my friends. Helper methods for java.

@Helper was introduced as an experimental feature in lombok v1.16.6.

Experimental

  • Lambdas with general function types offer an alternative strategy.
  • Perhaps a way to make helper methods with less boilerplate is possible, making this feature obsolete.

Overview

This annotation lets you put methods in methods. You might not know this, but you can declare classes inside methods, and the methods in this class can access any (effectively) final local variable or parameter defined and set before the declaration. Unfortunately, to actually call any methods you’d have to make an instance of this method local class first, but that’s where @Helper comes in and helps you out! Annotate a method local class with @Helper and it’s as if all the methods in that helper class are methods that you can call directly, just as if java had allowed methods to exist inside methods.

Normally you’d have to declare an instance of your helper, for example: HelperClass h = new HelperClass(); directly after declaring your helper class, and then call methods in your helper class with h.helperMethod(); . With @Helper , both of these things are no longer needed: You do not need to waste a line of code declaring an instance of the helper, and you don’t need to prefix all your calls to helper methods with nameOfHelperInstance.

Читайте также:  What is an argument or parameter in java

With Lombok

import lombok.experimental.Helper;

public class HelperExample <
int someMethod ( int arg1 ) <
int localVar = 5 ;

@Helper class Helpers <
int helperMethod ( int arg ) <
return arg + localVar;
>
>

return helperMethod ( 10 ) ;
>
>

Vanilla Java

public class HelperExample <
int someMethod ( int arg1 ) <
int localVar = 5 ;

class Helpers <
int helperMethod ( int arg ) <
return arg + localVar;
>
>
Helpers $Helpers = new Helpers () ;

return $Helpers.helperMethod ( 10 ) ;
>
>

Supported configuration keys:

lombok.helper.flagUsage = [ warning | error ] (default: not set) Lombok will flag any usage of @Helper as a warning or error if configured.

Small print

@Helper requires that the helper class has a no-args constructor. A compiler error will be generated if this is not the case.

Currently, the instance of your helper that’s made under the hood is called $Foo , where Foo is the name of your helper. We might change this in the future; please don’t rely on this variable existing. We might even replace this later with a sibling method instead.

Please don’t rely on this making any sense in the helper method code. You can refer to the real ‘this’ by using the syntax NameOfMyClass.this .

ANY unqualified method call in code that exists below the declaration of the helper method with the same name as any method in the helper is assumed to be a call to the helper. If the arguments don’t end up being compatible, you get a compiler error.

Unless you’re using JDK8 or higher (which introduced the concept of ‘effectively final’), you’ll have to declare local variables and parameters as final if you wish to refer to them in your method local class. This is a java limitation, not something specific to lombok’s @Helper .

Источник

Wildcard Capture and Helper Methods

In some cases, the compiler infers the type of a wildcard. For example, a list may be defined as List but, when evaluating an expression, the compiler infers a particular type from the code. This scenario is known as wildcard capture.

For the most part, you don’t need to worry about wildcard capture, except when you see an error message that contains the phrase «capture of».

The WildcardError example produces a capture error when compiled:

import java.util.List; public class WildcardError < void foo(Listi) < i.set(0, i.get(0)); >>

In this example, the compiler processes the i input parameter as being of type Object. When the foo method invokes List.set(int, E), the compiler is not able to confirm the type of object that is being inserted into the list, and an error is produced. When this type of error occurs it typically means that the compiler believes that you are assigning the wrong type to a variable. Generics were added to the Java language for this reason — to enforce type safety at compile time.

The WildcardError example generates the following error when compiled by Oracle’s JDK 7 javac implementation:

WildcardError.java:6: error: method set in interface List cannot be applied to given types; i.set(0, i.get(0)); ^ required: int,CAP#1 found: int,Object reason: actual argument Object cannot be converted to CAP#1 by method invocation conversion where E is a type-variable: E extends Object declared in interface List where CAP#1 is a fresh type-variable: CAP#1 extends Object from capture of ? 1 error

In this example, the code is attempting to perform a safe operation, so how can you work around the compiler error? You can fix it by writing a private helper method which captures the wildcard. In this case, you can work around the problem by creating the private helper method, fooHelper, as shown in WildcardFixed :

public class WildcardFixed < void foo(Listi) < fooHelper(i); >// Helper method created so that the wildcard can be captured // through type inference. private void fooHelper(List l) >

Thanks to the helper method, the compiler uses inference to determine that T is CAP#1, the capture variable, in the invocation. The example now compiles successfully.

By convention, helper methods are generally named originalMethodNameHelper.

Now consider a more complex example, WildcardErrorBad :

import java.util.List; public class WildcardErrorBad < void swapFirst(Listl1, List l2) < Number temp = l1.get(0); l1.set(0, l2.get(0)); // expected a CAP#1 extends Number, // got a CAP#2 extends Number; // same bound, but different types l2.set(0, temp); // expected a CAP#1 extends Number, // got a Number >>

In this example, the code is attempting an unsafe operation. For example, consider the following invocation of the swapFirst method:

List li = Arrays.asList(1, 2, 3); List ld = Arrays.asList(10.10, 20.20, 30.30); swapFirst(li, ld);

While List and List both fulfill the criteria of List , it is clearly incorrect to take an item from a list of Integer values and attempt to place it into a list of Double values.

Compiling the code with Oracle's JDK javac compiler produces the following error:

WildcardErrorBad.java:7: error: method set in interface List cannot be applied to given types; l1.set(0, l2.get(0)); // expected a CAP#1 extends Number, ^ required: int,CAP#1 found: int,Number reason: actual argument Number cannot be converted to CAP#1 by method invocation conversion where E is a type-variable: E extends Object declared in interface List where CAP#1 is a fresh type-variable: CAP#1 extends Number from capture of ? extends Number WildcardErrorBad.java:10: error: method set in interface List cannot be applied to given types; l2.set(0, temp); // expected a CAP#1 extends Number, ^ required: int,CAP#1 found: int,Number reason: actual argument Number cannot be converted to CAP#1 by method invocation conversion where E is a type-variable: E extends Object declared in interface List where CAP#1 is a fresh type-variable: CAP#1 extends Number from capture of ? extends Number WildcardErrorBad.java:15: error: method set in interface List cannot be applied to given types; i.set(0, i.get(0)); ^ required: int,CAP#1 found: int,Object reason: actual argument Object cannot be converted to CAP#1 by method invocation conversion where E is a type-variable: E extends Object declared in interface List where CAP#1 is a fresh type-variable: CAP#1 extends Object from capture of ? 3 errors

There is no helper method to work around the problem, because the code is fundamentally wrong: it is clearly incorrect to take an item from a list of Integer values and attempt to place it into a list of Double values.

Источник

Custom Helper Method in Java

Custom Helper Method in Java

  1. Helper Classes in Java
  2. Implementation of Helper Class in Java

We create a helper class to help provide capabilities that are not the primary goal of the implementation or class to which it is implemented.

In brief, the helper objects are instances of a helper class. In the delegation pattern, the same helper object has been used.

This demonstration will help you understand such a helper method by showing you the implementation from scratch.

Helper Classes in Java

We can create a custom helper class by making all its functions static and its function constructor private. Besides, we have the option to make the class final (if needed).

Hence, it cannot be initialized, but all methodologies can be directly accessed. In Java, a helper method is used to perform a specific repetitive task shared between multiple classes.

This restricts us from reiterating the same piece of code in multiple courses. At the same time, the class-specific methods define its conduct and the helper methods aid in that process.

Please check Helper Class for more info.

Relationship of Utility Class With Helper Class in Java

A utility class is a subset of a helper class in which all of the methods are static. In general, helper classes are not necessary to have all static methods, but they may encompass instance variables.

There may be lots of instances of the helper class.

Demonstration of the Utility Class:

public class CustomHelper   // Static function starts here  public static String funcOne (String str)   return "An apple a day, keeps doctor away " + str + "!"; > public static String funcTwo (String str)   return "Pie in the sky " + str + "!"; > public static String funcThree (String str)   return "ABCDEFGHIJKLMNOPQRSTUVWXYZ " + str + "!"; > > 

Since we will create our helper method using the helper class and the same corresponding method discussed so far. Then only you will be able to understand it fully.

Implementation of Helper Class in Java

Before further explaining, please look at the following code block of both files.

package helper.classdelfstack; public class DefineHelper   public static String str1(String print)   return "An apple a day" + print;  >  public static String str2(String print)   return "Out from the sky " + print;  >  public static String str3(String print)   return "Money makes " + print;  > > 

We have used public static for our main methods to initiate them with the main class.

package helper.classdelfstack;  public class RunHelper   public static void main(String[] args)   String print = " keeps doctor away!";  String print2 = " into the frying pan!";  String print3 = " mere go!";  System.out.println(DefineHelper.str1(print)); // An apple a day, keeps doctor away!  System.out.println(DefineHelper.str2(print2));  System.out.println(DefineHelper.str3(print3)); //  > > 

We run this custom helper class with the main function of RunHelper.java .

An apple a day keeps doctor away! Out from the sky into the frying pan! Money makes mere go! 

If you look closely, you’ll notice that we created a simple class, DefineHelper , consisting of helper methods. This class could be used in multiple classes.

Now, if you look at the RunHelper class, you’ll notice that we’ve added the following:

So, when we run it, we can access the RunHelper class, but we can also prepend the DefineHelper strings with constructors.

If we want to create more classes like these, all we have to do is implement the same helper methods for them. So, we would be capable of creating a personalized library of methods for use in our projects.

This type of elementary-level program can be expanded into a comprehensive library. This way, you can put a Java helper class to good use.

Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.

Related Article - Java Method

Источник

Оцените статью