Search code examples
javadynamicmethodsmethodology

Dynamic dot method call


This is a general Java programming question presented through its application in my current program (specifying a page's size).

I have always wanted to implement dynamic references into .methods but it doesn't seem very feasible.

In my current program The user is presented with a dropdown menu. From the menu they select a page size (A1, B2, A3...).Then I need to do this line:

Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);

Can I replace the A4 with a dynamic reference? Otherwise I need to call this same line in as many separate sections as there are page sizes.

Something like this does not seem to work:

Rectangle f = new Rectangle();
Document document = new Document(PageSize.f.rotate(), 50, 50, 50, 50);

so I'm guessing this methodology is not possible. But if things can be done this way I'd love to know how. For now I'm going to set the contents of the parenthesis (PageSize.f.rotate(), 50, 50, 50, 50) as a variable and drop that in.

So can methods only use dynamic references when they have parenthesis to take in variables, or can dynamic references be used in .method calls as well?

Thank you in advance for any help, it's always very much appreciated.


Update: Solution...

com.itextpdf.text.Rectangle selectedPageSize = PageSize.A10; Document document = new Document(selectedPageSize.rotate(), 50, 50, 50, 50);


Solution

  • You can store PageSize.A4 in a variable, just like any other expression.

    You can then store that value in your dropdown menu item.