i am go through the below method but not getting how my seniors designed.
public LinkedHashMap<String,IPDFField> getFields() {
LinkedHashMap<String, IPDFField> fields = new LinkedHashMap<String, IPDFField>();
//^field1c^lastName^nameSuffix
// Line One
addField(fields,"1_1", new PDFField(27+X_OFF, 718+Y_OFF, new FieldWidthValidation(134F, "^field1_1^firstName^middleName^lastName^nameSuffix")) { //PI tab
#Override
public String getPrintableText(Object o) {
Disposition d = (Disposition) o;
return dataFormattingService.NormalizedPersonName(
d.getFirstName(), d.getMiddleName(), d.getLastName(), d.getNameSuffix()
);
}
});
} //getFileds method ends
from above method they have called below addField Method but what is getPrintableText inside AddField Method
private void addField(HashMap<String, IPDFField> fields, String fieldKey, IPDFField field) {
field.setFieldKey(fieldKey);
if (field.getValidation() != null) {
field.getValidation().setField(field);
}
fields.put(fieldKey, field);
}
above is not full code , the main functionality is we are trying to write content into pdf but i don't want to paste my full code i just need explanation for above logic
addField(/**/, new PDFField(/**/) {
#Override
public String getPrintableText(Object o) {
// ...
}
});
What happens here is the creation of an anonymous inner class.
This anonymous inner class extends the class PDFField and redefines the behavior of the method getPrintableText which is defined in class PDFField.
sorry one more doubt addFiled we have two methods in above , one is anonymous and another is private method,may i know if they are using annonymous class then they could have declared different method name for addField which is private above? – adithyan .p
I'm not sure if I understand that comment...
The anonymous class is
new PDFField(/**/) {
#Override
public String getPrintableText(Object o) {
// ...
}
}
And this is passed as a parameter to the method addField().
There is no restriction on the visibility of the method that gets the anonymous class instance as a parameter.
Related
I want to achieve method chaining in Java.
How can I achieve it?
Also let me know when to use it.
public class Dialog {
public Dialog() {
}
public void setTitle(String title) {
//Logic to set title in dialog
}
public void setMessage(String message) {
//Logic to set message
}
public void setPositiveButton() {
//Logic to send button
}
}
I want to create method chaining that I can use as follows:
new Dialog().setTitle("Title1").setMessage("sample message").setPositiveButton();
or like
new Dialog().setTitle("Title1").setMessage("sample message");
or like
new Dialog().setTitle("Title1").setPositiveButton();
Have your methods return this like:
public Dialog setMessage(String message)
{
//logic to set message
return this;
}
This way, after each call to one of the methods, you'll get the same object returned so that you can call another method on.
This technique is useful when you want to call a series of methods on an object: it reduces the amount of code required to achieve that and allows you to have a single returned value after the chain of methods.
An example of reducing the amount of code required to show a dialog would be:
// Your Dialog has a method show()
// You could show a dialog like this:
new Dialog().setMessage("some message").setTitle("some title")).show();
An example of using the single returned value would be:
// In another class, you have a method showDialog(Dialog)
// Thus you can do:
showDialog(new Dialog().setMessage("some message").setTitle("some title"));
An example of using the Builder pattern that Dennis mentioned in the comment on your question:
new DialogBuilder().setMessage("some message").setTitle("some title").build().show();
The builder pattern allows you to set all parameters for a new instance of a class before the object is being built (consider classes that have final fields or objects for which setting a value after it's been built is more costly than setting it when it's constructed).
In the example above: setMessage(String), setTitle(String) belong to the DialogBuilder class and return the same instance of DialogBuilder that they're called upon; the build() method belongs to the DialogBuilder class, but returns a Dialog object the show() method belongs to the Dialog class.
Extra
This might not be related to your question, but it might help you and others that come across this question.
This works well for most use cases: all use cases that don't involve inheritance and some particular cases involving inheritance when the derived class doesn't add new methods that you want to chain together and you're not interested in using (without casting) the result of the chain of methods as an object of the derived.
If you want to have method chaining for objects of derived classes that don't have a method in their base class or you want the chain of methods to return the object as a reference of the derived class, you can have a look at the answers for this question.
Just add a static builder method, and create another set of the setter methods.
For example
class Model {
private Object FieldA;
private Object FieldB;
public static Model create() {
return new Model();
}
public Model withFieldA(Object value) {
setFieldA(value);
return this;
}
public Model withFieldB(Object value) {
setFieldB(value);
return this;
}
}
...
And use it like
Model m = Model.create().withFieldA("AAAA").withFieldB(1234);
example of reducing the amount of code required to show a dialog would be:
package com.rsa.arraytesting;
public class ExampleJavaArray {
String age;
String name;
public ExampleJavaArray getAge() {
this.age = "25";
return this;
}
public ExampleJavaArray setName(String name) {
this.name = name;
return this;
}
public void displayValue() {
System.out.println("Name:" + name + "\n\n" + "Age:" + age);
}
}
another class
package com.rsa.arraytesting;
public class MethodChaining {
public static void main(String[] args) {
ExampleJavaArray mExampleJavaArray = new ExampleJavaArray();
mExampleJavaArray.setName("chandru").getAge().displayValue();
}
}
In case if you are using lombok, you can use parameter in your lombok.config:
lombok.accessors.chain = true
Or for particular data classes you can declare #Accessors(chain = true) annotation:
import lombok.experimental.Accessors;
#Accessors(chain = true)
#Data
public class DataType {
private int value;
// will generate setter:
public DataType setValue(int value) {
this.value = value;
return this;
}
}
I want to achieve method chaining in Java.
How can I achieve it?
Also let me know when to use it.
public class Dialog {
public Dialog() {
}
public void setTitle(String title) {
//Logic to set title in dialog
}
public void setMessage(String message) {
//Logic to set message
}
public void setPositiveButton() {
//Logic to send button
}
}
I want to create method chaining that I can use as follows:
new Dialog().setTitle("Title1").setMessage("sample message").setPositiveButton();
or like
new Dialog().setTitle("Title1").setMessage("sample message");
or like
new Dialog().setTitle("Title1").setPositiveButton();
Have your methods return this like:
public Dialog setMessage(String message)
{
//logic to set message
return this;
}
This way, after each call to one of the methods, you'll get the same object returned so that you can call another method on.
This technique is useful when you want to call a series of methods on an object: it reduces the amount of code required to achieve that and allows you to have a single returned value after the chain of methods.
An example of reducing the amount of code required to show a dialog would be:
// Your Dialog has a method show()
// You could show a dialog like this:
new Dialog().setMessage("some message").setTitle("some title")).show();
An example of using the single returned value would be:
// In another class, you have a method showDialog(Dialog)
// Thus you can do:
showDialog(new Dialog().setMessage("some message").setTitle("some title"));
An example of using the Builder pattern that Dennis mentioned in the comment on your question:
new DialogBuilder().setMessage("some message").setTitle("some title").build().show();
The builder pattern allows you to set all parameters for a new instance of a class before the object is being built (consider classes that have final fields or objects for which setting a value after it's been built is more costly than setting it when it's constructed).
In the example above: setMessage(String), setTitle(String) belong to the DialogBuilder class and return the same instance of DialogBuilder that they're called upon; the build() method belongs to the DialogBuilder class, but returns a Dialog object the show() method belongs to the Dialog class.
Extra
This might not be related to your question, but it might help you and others that come across this question.
This works well for most use cases: all use cases that don't involve inheritance and some particular cases involving inheritance when the derived class doesn't add new methods that you want to chain together and you're not interested in using (without casting) the result of the chain of methods as an object of the derived.
If you want to have method chaining for objects of derived classes that don't have a method in their base class or you want the chain of methods to return the object as a reference of the derived class, you can have a look at the answers for this question.
Just add a static builder method, and create another set of the setter methods.
For example
class Model {
private Object FieldA;
private Object FieldB;
public static Model create() {
return new Model();
}
public Model withFieldA(Object value) {
setFieldA(value);
return this;
}
public Model withFieldB(Object value) {
setFieldB(value);
return this;
}
}
...
And use it like
Model m = Model.create().withFieldA("AAAA").withFieldB(1234);
example of reducing the amount of code required to show a dialog would be:
package com.rsa.arraytesting;
public class ExampleJavaArray {
String age;
String name;
public ExampleJavaArray getAge() {
this.age = "25";
return this;
}
public ExampleJavaArray setName(String name) {
this.name = name;
return this;
}
public void displayValue() {
System.out.println("Name:" + name + "\n\n" + "Age:" + age);
}
}
another class
package com.rsa.arraytesting;
public class MethodChaining {
public static void main(String[] args) {
ExampleJavaArray mExampleJavaArray = new ExampleJavaArray();
mExampleJavaArray.setName("chandru").getAge().displayValue();
}
}
In case if you are using lombok, you can use parameter in your lombok.config:
lombok.accessors.chain = true
Or for particular data classes you can declare #Accessors(chain = true) annotation:
import lombok.experimental.Accessors;
#Accessors(chain = true)
#Data
public class DataType {
private int value;
// will generate setter:
public DataType setValue(int value) {
this.value = value;
return this;
}
}
I want to achieve method chaining in Java.
How can I achieve it?
Also let me know when to use it.
public class Dialog {
public Dialog() {
}
public void setTitle(String title) {
//Logic to set title in dialog
}
public void setMessage(String message) {
//Logic to set message
}
public void setPositiveButton() {
//Logic to send button
}
}
I want to create method chaining that I can use as follows:
new Dialog().setTitle("Title1").setMessage("sample message").setPositiveButton();
or like
new Dialog().setTitle("Title1").setMessage("sample message");
or like
new Dialog().setTitle("Title1").setPositiveButton();
Have your methods return this like:
public Dialog setMessage(String message)
{
//logic to set message
return this;
}
This way, after each call to one of the methods, you'll get the same object returned so that you can call another method on.
This technique is useful when you want to call a series of methods on an object: it reduces the amount of code required to achieve that and allows you to have a single returned value after the chain of methods.
An example of reducing the amount of code required to show a dialog would be:
// Your Dialog has a method show()
// You could show a dialog like this:
new Dialog().setMessage("some message").setTitle("some title")).show();
An example of using the single returned value would be:
// In another class, you have a method showDialog(Dialog)
// Thus you can do:
showDialog(new Dialog().setMessage("some message").setTitle("some title"));
An example of using the Builder pattern that Dennis mentioned in the comment on your question:
new DialogBuilder().setMessage("some message").setTitle("some title").build().show();
The builder pattern allows you to set all parameters for a new instance of a class before the object is being built (consider classes that have final fields or objects for which setting a value after it's been built is more costly than setting it when it's constructed).
In the example above: setMessage(String), setTitle(String) belong to the DialogBuilder class and return the same instance of DialogBuilder that they're called upon; the build() method belongs to the DialogBuilder class, but returns a Dialog object the show() method belongs to the Dialog class.
Extra
This might not be related to your question, but it might help you and others that come across this question.
This works well for most use cases: all use cases that don't involve inheritance and some particular cases involving inheritance when the derived class doesn't add new methods that you want to chain together and you're not interested in using (without casting) the result of the chain of methods as an object of the derived.
If you want to have method chaining for objects of derived classes that don't have a method in their base class or you want the chain of methods to return the object as a reference of the derived class, you can have a look at the answers for this question.
Just add a static builder method, and create another set of the setter methods.
For example
class Model {
private Object FieldA;
private Object FieldB;
public static Model create() {
return new Model();
}
public Model withFieldA(Object value) {
setFieldA(value);
return this;
}
public Model withFieldB(Object value) {
setFieldB(value);
return this;
}
}
...
And use it like
Model m = Model.create().withFieldA("AAAA").withFieldB(1234);
example of reducing the amount of code required to show a dialog would be:
package com.rsa.arraytesting;
public class ExampleJavaArray {
String age;
String name;
public ExampleJavaArray getAge() {
this.age = "25";
return this;
}
public ExampleJavaArray setName(String name) {
this.name = name;
return this;
}
public void displayValue() {
System.out.println("Name:" + name + "\n\n" + "Age:" + age);
}
}
another class
package com.rsa.arraytesting;
public class MethodChaining {
public static void main(String[] args) {
ExampleJavaArray mExampleJavaArray = new ExampleJavaArray();
mExampleJavaArray.setName("chandru").getAge().displayValue();
}
}
In case if you are using lombok, you can use parameter in your lombok.config:
lombok.accessors.chain = true
Or for particular data classes you can declare #Accessors(chain = true) annotation:
import lombok.experimental.Accessors;
#Accessors(chain = true)
#Data
public class DataType {
private int value;
// will generate setter:
public DataType setValue(int value) {
this.value = value;
return this;
}
}
I have got some methods that are common to two subclasses so i have put them in Abstract superclass but there is one method that uses a variable with two different values so i am confused how to implement that method the code is like:
StandardMember class got this method with its own different value for remainingCredit=30 at starting
public void borrowHolding(int holdingId)
throws InsufficientCreditException, MultipleBorrowingException {
// TODO Auto-generated method stub
System.out.println("Hello");
Holding tempHolding = Library.libCollection.getHolding(holdingId);
if (Library.libCollection.getHolding(holdingId) != null) {
if (tempHolding.isOnLoan()) {
System.out.println("Can not be issued Currently on Load");
} else {
System.out.println("Can be issued");
remainingCredit-=tempHolding.getDefaultLoanFee();
System.out.println(getRemainingCredit());
tempHolding.setLoanCheck(true);
currentlyBorrowedHolding.put(holdingId, tempHolding);
System.out.println(remainingCredit);
System.out.println(holdingId);
}
}
PremiumMember Class got same method but the value of remainingCredit is 45, Whereas all the methods common to them are implemented in this AbstractMember class which implements the Member interface. but when i try to call these method from other class i have to initialize the object of AbstractMember in Library Class like this
Member member = new StandardMember();
which is very bad because I can not use the StandardMember object to run the PremiumMember Object's version of same method. so, either i should create new object of PremiumMember Class or i dont know what to do. but if i create two objects then this member object is being used in borrowHolding method which is basically a cascading method in Library Class which in turn calls the borrowHolding method in Member Interface:
public void borrowHolding(int holdingId) throws InsufficientCreditException, MultipleBorrowingException {
if(libCollection.holdingMap==null){
System.out.println("Collection is Empty");
}
if(libCollection.holdingMap.containsKey(holdingId))
member.borrowHolding(holdingId);
}
the problem is i can not create two objects because at runtime i can only call one method. so help me out how to implement this method in Abstract class so that program will detect the difference that which object it should create.
If I understood you correctly, you have a Member abstract class with a field remainingCredit which has to be 30 in one subclass and 45 in another.
Use a protected constructor.
public abstract class Member {
private int remainingCredit;
// Other members
// getters and setters
protected Member(String memId, String memName, int remainingCredit) {
this.memId = memId;
this.memName = memName;
this.remainingCredit = remainingCredit;
}
}
public StandardMember extends Member {
public StandardMember(String memId, String memName) {
super(memId, memName, 30);
}
}
public PremiumMember extends Member {
public PremiumMember(String memId, String memName) {
super(memId, memName, 45);
}
}
I want to apologize for the title, but I didn't know how to summarise this problem.
I've got the following class called AbstractWriter:
public class AbstractWriter {
private boolean changePerformed = false;
// Some Setters
private void changePerformed() {
if (!changePerformed)
changePerformed = true;
}
public boolean isChangePerformed() {
return changePerformed;
}
protected <S> void setValue(
Class<S> type, Object oldValue, Object newValue, Setter setter) {
// Do something
changePerformed();
}
}
Whenever a setter is called, the method setValue(…) is invoked. All setter implement this rule.
Then there's AgeWriter, extended from AbstractWriter:
public class AgeWriter extends AbstractWriter {
// Some Setters
}
And then again, there's HumanWriter:
public class HumanWriter {
// Some setter calls are delegated to this Writer
private AgeWriter ageWriter = new AgeWriter();
// Some Setters
}
When I now invoke the method isChangePerformed() on HumanWriter, I only know if a setter on HumanWriter has been called, but not if one of those delegate setters to AgeWriter.
I'm now looking for a general way to solve this problem. Here are some ways I tried respectively thought about:
Try to find all members of type AbstractWriter with Reflection. But getDeclardFields misses out on inherited ones and getFields on private ones.
Make isChangePerformed() abstract so that every implementation has to make sure it's implemented correct.
Create the abstract method getAbstractWriters that returns all AbstractWriters used inside this type.
What would be your ideas to solve this problem?
If you keep the ageWriter private to HumanWriter, there is no way any external object calls a setter on AgeWriter directly. Use encapsulation, by not providing any accessor to the ageWriter, and use methods on HumanWriter that delegate to the ageWriter.
You could also use an observable/observer pattern (JavaBeans property change listeners) and add the HumanWriter as a listener to the AgeWriter. This way, every property change on the ageWriter will trigger an event that will be sent to the HumanWriter.
My idea may be stupid. But I thing it should work:). You can use the list of writers...
public abstract class AbstractWriter {
private List<AbstractWriter> writers;
//...
private boolean changePerformed = false;
//...
public boolean isChangePerformed() {
for (AbstractWriter writer : writers) {
if(writer.isChangePerformed() && changePerformed) {
return true;
}
}
return false;
}
}