HasURLParameter and call order of setParameter Method

Hello,

for example:

	
@Route("myClass")
public class MyClass extends HorizontalLayout implements HasUrlParameter<String>{

	String objectId;

	@Override
	public void setParameter(BeforeEvent event, String parameter) {
		objectId = parameter;
		System.out.println("setParameter() Method: " + objectId);
	}
	
	public MyClass(){
		
		System.out.println("constructor: " + objectId);
		MyObject  = getMyObject(objectId);
	}
}

Output:

constructor: null
setParameter() Method: 1

Is there a way to get the UrlParamater before the constructor? Otherwise, MyObject is null.
Can anyone help me?

Thanks in advance.

No. In Java, a constructor must be called before any non-static methods. You’ll need to reorder your logic.

You can load your object in afterNavigation.
You can see the documentation here:
https://vaadin.com/docs/v14/flow/routing/tutorial-routing-lifecycle/#afternavigationevent

Olli Tietäväinen:
No. In Java, a constructor must be called before any non-static methods. You’ll need to reorder your logic.

Ok, how can I build a Java Class/Route with Vaadin, which allows me to work with a parameter from URL? I have to get the parameter from URL already before constructor, which should allow me to get an Object with this parameter from URL. What would you recommend for me?

The setParameter is always called after the constructor. You can’t call a method of an object before building the object.


@Route("myClass")
public class MyClass extends HorizontalLayout implements HasUrlParameter<String>, AfterNavigationObserver {

	private String objectId;
	private MyObject myObject;

	public MyClass(){
		
	}
	
	@Override
	public void setParameter(BeforeEvent event, String parameter) {
		objectId = parameter;
		System.out.println("setParameter() Method: " + objectId);
	}
	
	 @Override
    public void afterNavigation(
          AfterNavigationEvent event) {
		System.out.println("afterNavigation: " + objectId);
		myObject  = getMyObject(objectId);
    }
	...
}

Thanks, it works after reordering my logic. So I copied everything that was in the constructor into the setParameter (BeforeEvent event, String parameter) method and it works without any problems.

tanks