0

Hi i'm new to jsf/el and i'm looking for a solution to pass a class ex : "Student.class" as a method parameter to my method defined in my backing bean. By the way i tested the same overloaded method using a string parameter without any issues but i prefer a Class parameter over a String parameter for my use case.

MyBean.java:

public void createPersonType(Class className) {
    // Person factory code goes here
}

person.xhtml:

<... actionListener="#{myBean.createPersonType(Student.class)}" />

Any suggestions are welcome. Thank you.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user3072470
  • 131
  • 2
  • 11
  • I don't think EL allows that. Why not create overloaded methods like `createStudent()`. Your MenuItem is already specific why not have it call a specific method. – Melloware Mar 20 '21 at 15:18

2 Answers2

1

This is not supported in EL.

Just use an enum instead if you want to enforce type safety.

public interface Person {

    public enum Type {
        STUDENT, TEACHER, ETC;
    }

    public Type getType();
}
public void createPersonType(Person.Type personType) {
    // Person factory code goes here
}
<... actionListener="#{myBean.createPersonType('STUDENT')}" />

JSF will automatically convert the string to actual enum.

Instead of the string, you can also use <f:importConstants> (or <o:importConstants>).

<f:metadata>
    <f:importConstants type="com.example.Person.Type" var="PersonType" />
</f:metadata>
...
<... actionListener="#{myBean.createPersonType(PersonType.STUDENT)}" />

See also:

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
-1

You could pass the whole class reference your.package.Student as a String. Your method would look like this:

public void createPersonType(String className) {
    Class<?> class = Class.forName(className);
}
semrola
  • 9
  • 4
  • From the question: *"By the way i tested the same overloaded method using a string parameter without any issues but i prefer a Class parameter over a String parameter for my use case."*. – BalusC Mar 22 '21 at 09:36
  • Oh my bad, I somehow missed that part. – semrola Mar 22 '21 at 12:23