Question

I'm writing a Login page in wicket by java and want to write it as general as possible so I need to pass to class a function which famous as Function Pointer in C++. The class is:

class LoginForm extends Form
{

    public LoginForm(String id,TextField username,TextField password,WebResponse webResponse)
    {
        super(id);
    }

    @Override
    public void onSubmit()
    {
        String password = Login.this.getPassword();
        String userId = Login.this.getUserId();
        String role = authenticate(userId, password);
        if (role != null)
        {
            if (Login.this.getSave())
            {
                utilities.CreateCookie("Username", userId, false, 1209600, (WebResponse) getRequestCycle().getResponse());
                utilities.CreateCookie("Password", password, false, 1209600, (WebResponse) getRequestCycle().getResponse());
            }
            User loggedInUser = new User(userId, role);
            WiaSession session = (WiaSession) getSession();
            session.setUser(loggedInUser);
            if (!continueToOriginalDestination())
            {
                setResponsePage(UserHome.class);
            }
        }
        else
        {
            wrongUserPass.setVisible(true);
        }
    }
}

where authenticate is that function what should I do?

Was it helpful?

Solution

Just pass an Interface which defines the authenticate method.

void DoSomething(IAuthenticationProvider authProvider) {
    // ...
    authProvider.authenticate();
}

OTHER TIPS

You can use inner class

In java there is nothing call function pointer rather it is function object. In this you can define object whose methods performs operation on the other objects. e.g.

 class MyClass 
 {
      public void myFunction(String s1, String s2)
      { 
           return s1.length() - s2.length();
      }
 }

 MyClass m = new MyClass(); 
 m.myFunction("nnnnnn", "mmmmmmmmmmm");

This is nothing but function object. If we follow code to interface rule then we can define an interface and can use generics as well.

 public interface MyInterface<T>
 {
      public void myFunction(T s1, T s2);
 }

Now the original class can implement this interface. The above example is just a simple modification of Comparator interface example. If you don't want concrete class you can use anonymous class as well.

Arrays.sort(stringArray, new Comparator <String> ()
  {
       public int compare(String s1, String s2)
             {
                   return s1.length() - s2.length();
             }
  };
  );

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top