Pega is built so you can do almost everything with rules, but sometimes an activity needs a few lines of Java. The Java step method is how you add them.
How to add Java to an activity
- Open the activity and add a step.
- In the Method column, choose Java.
- Click the gear or arrow icon next to the step to open the Java editor.
- Type the code and save. Pega compiles it when you save the rule.
The variable you use most: tools
Inside a Java step you get a tools object that gives you access to the current thread and the clipboard. For example, to read a property from a named page:
ClipboardPage page = tools.findPage("pyWorkPage");
String id = page.getString("pyID");
log.infoForced("Working on case " + id);
Notice that the property name has no leading dot when you use the Java API. Other common calls are page.putString("Status", "Open") to set a value and tools.getPrimaryPage() to get the page the activity is running on.
A worked example
A bank needs to build a reference number that combines the branch code, the year and a padded sequence number, for example BR12-2026-000457. A data transform can do most of it, but the padding is easier in Java:
ClipboardPage work = tools.getPrimaryPage();
String branch = work.getString("BranchCode");
int seq = Integer.parseInt(work.getString("Sequence"));
String ref = branch + "-" + java.time.Year.now() + "-" + String.format("%06d", seq);
work.putString("ReferenceNumber", ref);
Guardrails: use it sparingly
- Pega's guardrails warn against custom Java. Use it only when no out-of-the-box method or function does the job.
- Prefer a function rule if the same code is needed in several places, so it is written once and tested once.
- Custom Java is harder to read, harder to upgrade, and skips the rule-level tracing you get from normal steps.
- Never put secrets, long-running loops or direct JDBC calls in a Java step.
Interview tip
The interviewer wants to hear that you know how, and also that you know when not to. Say: "You use the Java method, but I would first look for a standard method or a function, because guardrails discourage custom Java." Continue with the Activity label.
No comments:
Post a Comment