Generate custom Java Getters and Setters - java

I want to generate custom getters and setter, so I can handle variables better when I will be saving these instances into SQL database. I want to generate something like:
public class Test extends SQLEntry {
private static final String NAME = "Name";
public String getName() {
return get(NAME);
}
public void setName(String name) {
set(NAME, name);
}
}
But as I can see in Eclipse it generates only the following code:
public class Test {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Is there some plugin, that can do it? Or am I missing something?
I have like 20 classes and I will not write this manually.

I dont know why you need this, but here is the approach to custom Getters and Setters.
You can update all generated setters and getters by going to preferences > java > Code Style > code Templates and selecting code then edit Getter body and Setter body and put this:
Getter body: return get(${field});
Setter body: set(${field}, ${param});
Let me know if that works

I recommend that instead of doing what you describe, you should use Spring Data. Specifically the BeanPropertyRowMapper class in the org.springframework.jdbc.core package will do what you want.
Read more in the Spring API documentation.

there is no other plugin available!
how can some plugin write code that is specific to your business logic!
you have to write the code manually for setters and getters in all the classes!

Try write-it-once. Template based code generator. You write custom template using Groovy, and generate file depending on java reflections. It's the simplest way to generate any file. You can make getters/settest/toString by generating AspectJ or java files, SQL based on JPA annotations, inserts / updates based on enums and so on.

On the end I found it that it is the best to do it your self...
If you like writing a code than you will enjoy this solution the most.
public class CodeGenerator {
private final static String ENCODING = "UTF-8";
private final static String FILE_NAME = "File.txt";
public static void main(String[] args) {
try {
ArrayList<Carriage> names = getNames();
for (Carriage c : names) {
createSetter(c.name, c.capitalName);
createGetter(c.name, c.capitalName);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
private static ArrayList<Carriage> getNames() throws FileNotFoundException {
File file = new File("/");
InputStream is = CodeGenerator.class.getResourceAsStream(FILE_NAME);
Scanner s = new java.util.Scanner(is, ENCODING).useDelimiter("\\A");
String content = s.next();
String[] lines = content.split(System.getProperty("line.separator"));
ArrayList<Carriage> ret = new ArrayList<Carriage>();
for (String line : lines) {
line = line.replaceAll("\\r", "");
int firstCapitalIndex = line.indexOf("String") + 7;
int secondCapitalIndex = line.indexOf(" ", firstCapitalIndex);
int firstIndex = line.indexOf("\"") + 1;
int secondIndex = line.indexOf("\"", firstIndex + 1);
Carriage c = new Carriage();
c.name = line.substring(firstIndex, secondIndex);
c.capitalName = line.substring(firstCapitalIndex, secondCapitalIndex);
ret.add(c);
}
return ret;
}
public static void createSetter(String name, String capitalName) {
String str = "public void set" + name + "(String val) {\n"
+ "\tset(" + capitalName + ", val);\n"
+ "}\n";
System.out.println(str);
}
public static void createGetter(String name, String capitalName) {
String str = "public String get" + name + "() {\n"
+ "\treturn (String) get(" + capitalName + ");\n"
+ "}\n";
System.out.println(str);
}
carriage:
package codegenerator;
public class Carriage {
public String name;
public String capitalName;
}
And to File.txt I just coppy all defined constants and run the generator...
public static final String NAME = "Name";
public static final String PHONE = "Phone";
public static final String EMAIL = "Email";
public static final String ADDRESS_1 = "Address1";
public static final String ADDRESS_2 = "Address2";
public static final String ADDRESS_3 = "Address3";
public static final String ICO = "Ico";
public static final String DIC = "Dic";
public static final String ADMIN_LOGIN = "AdminLogin";
public static final String ADMIN_PASSWORD = "AdminPassword";
public static final String LANGUAGE = "Language";
public static final String CODE = "CODE";
public static final String MONTHLY_PAYMENT = "MonthlyPayment";

Related

how can replace more then 16 if else-if statement Java

Im trying to make a program that allows the client to input a String. The string length should have 3 characters only and should contain the letters .
My program have to pass through this table and check what this string refers to..
Let's say the client passed this String "AUG", my program should show the name of this String which is "Met".
I made a code, and it worked but it has more then 15 if else-if condition.
My question is : Is there any other way to do it without using if else-if (or switch).
And does polymorphism work in this case ?
Have a look at HashMap
You can build your table with:
Map<String, String> table = new HashMap<>();
table.put("AUG", "Met");
table.put(...);
Then access your table using the user's input:
if(table.containsKey(input)){
return table.get(input);
}
I think I'd go about it with an enum personally (provided performance wasn't a significant concern):
public enum Abbreviations {
Ala("GCU", "GCC", "GCA", "GCG"),
Arg("CGU", "CGC", "CGA", "CGG", "AGA", "AGG")
// ...
;
private final List<String> codons;
private Abbreviations(final String... codons) {
this.codons = Arrays.asList(codons);
}
public boolean contains(final String codon) {
return this.codons.contains(codon);
}
}
And then you can find their matching from the String using something like:
public String find(final String codon) {
for (final Abbreviations abb : Abbreviations.values()) {
if (abb.contains(codon)) {
return abb.name();
}
}
throw new IllegalArgumentException("Unknown codon: '" + codon + "'");
}
You could try an Object Oriented Aproach:
//This is your representation of Codon
//Which has a name e.g. Alanine and an Abreviation object.
public class Codon {
private String name;
private Abreviation abreviation;
public Codon(String name, Abreviation abreviation) {
this.name = name;
this.abreviation = abreviation;
this.abreviation.addCodon(this);
}
#Override
public String toString() {
return "Codon [name=" + name + ", abreviation=" + abreviation + "]";
}
}
import java.util.ArrayList;
import java.util.List;
// This is a representation of an abreviation object
// Which has an abreviation: ALA;
// and the name of the abreviation "Alanine".
public class Abreviation {
private String abreviation;
private String name;
private List<Codon> codons = new ArrayList<>();
public Abreviation(String abreviation, String name) {
super();
this.abreviation = abreviation;
this.name = name;
}
public boolean addCodon(Codon codon) {
return this.codons.add(codon);
}
#Override
public String toString() {
return "Abreviation [abreviation=" + abreviation + ", name=" + name + "]";
}
}
// Here is your program, where it's being build all the Codons structure with your respective Abbreviation.
public class App {
public static void main(String[] args) {
// This is abreviation, it'll will associated with the codon
Abreviation alanine = new Abreviation("Ala", "Alanine");
// Here it's being build the codon CGU, which has abreviation alanine
Codon GCU = new Codon("GCU", alanine);
// Then using toString method it prints what have been done
System.out.println(GCU);
}
}
You can put all of your codons into a List, so you can search and retrieve then.

Multiple values for a single parameter

How to pass multiple values to a single parameter for a particular method in java.
e.g. suppose i have a method with single parameter 'childname', that gets names of all the children in a family.
Now how can i pass multiple values to this parameter to get all different names.
public String getChildrenNames(String childname)
{
children= childname+ familyName;
return children;
}
You would typically implement this using either an Array, or a Collection.
eg:
public String[] getNamesOfChildren()
or
public Collection<String> getNamesOfChildren()
As people say you need to pass them as an Array, so your code should be like this:
String familyName = "Family";
public String[] getChildrenNames(String[] childnames)
{
String[] result = new String[childnames.length];
for(int i=0; i<childnames.length; i++)
{
result[i] = childnames[i] + " " +familyName;
}
return result;
}
public void main()
{
String[] childnames = {"Name1", "Name2", "Name3"};
String[] childnamesAux = getChildrenNames(childnames);
}
With this your childnamesAux variable should have: {"Name1 Family", "Name2 Family", "Name3 Family"}
If you can't change the signature of your method, then you can use concatenation, then in your method you can split this parameter for example :
String childname = firstname + "," + lastname;
getChildrenNames(childname);
so you can split this parametter to get multiple names,
String[] spl = childname.split(",");
But there are better ways then this, if you can change the signature of your method, so you can create a method which can take an array or list of names instead :
public String getChildrenNames(String...childnames) {
or
public String getChildrenNames(Lis<String> childnames) {
You can even create an Object for example :
class Person{
private String firstname;
private String lastname;
//getters and setters
}
Then your method should take an array or a list of Person Object :
public String getChildrenNames(List<Person> childname) {
You can try this
public static String child(String... name){
String[] array=name;
String tem;
if(name.length==1)
return name[0];
for(int counter=0; counter<array.length;counter+=2){
array[0]=name[counter]+name[counter+1];
}
tem=array[0];
return tem;
}
now if you call it
child("Paul","walker");
the output will be
Paul Walker
hope this helped
you can use var args like below
public String getChildrenNames(String... childname)
{
for(String s:childname)
{
children= childname+ s;
}
return children;
}
example
public class Test {
public static void main(String[] args) {
System.out.println(tes("s","d","s"));
}
static String tes(String... x)
{
String y="";
for(String s:x)
{
y=y+s;
}
return y;
}
}
output: sds

Java, static variable doesn't initialize from outside of class

I have a class that all of its methods and variables are static. Class is like this:
public class LinkManager {
private static final String TAG = "LinkManager";
private static final String UAT = "http://uat.MY-Domain.com/";
private static final String PRODUCTION = "https://www.MY-Domain.com/api/";
private static String DOMAIN;
private static final String FACEBOOK_PROFILE_IMAGE_URL = "http://graph.facebook.com/###/picture?type=large";
private static final String FACEBOOK_WALL_URL = "https://graph.facebook.com/###/feed";
private static final String URL_LOGIN = DOMAIN + "login/";
private static final String URL_USER_PROFILE = DOMAIN + "user/";
private static final String URL_VENUE_LIST = DOMAIN + "venues/?centre_lat=###&centre_lon=####&radius=#####";
.
.
.
public static void setBackendMode(int mode) {
switch(mode) {
case 0:
DOMAIN = PRODUCTION;
Log.i(TAG, "Backend mode: Production");
break;
case 1:
DOMAIN = UAT;
Log.i(TAG, "Backend mode: UAT");
break;
default:
Log.e(TAG, "Fatal Error!!! Check you backend url. Selected mode is: " + mode);
}
}
public static String getFacebookProfileImageUrl(String userId) {
String str = FACEBOOK_PROFILE_IMAGE_URL;
str = str.replaceAll("###", userId);
return str;
}
public static String getFacebookWallUrl(String userId) {
String str = FACEBOOK_WALL_URL;
str = str.replaceAll("###", userId);
return str;
}
public static String getLoginUrl() {
return URL_LOGIN;
}
public static String getUserProfileUrl() {
return URL_USER_PROFILE;
}
public static String getVenueListUrl(String lat, String lng, String radius) {
String str = URL_VENUE_LIST;
str = str.replaceAll("###", lat);
str = str.replaceAll("####", lng);
str = str.replaceAll("#####", radius);
return str;
}
.
.
.
}
I have another class which is my main class. I want to initialize DOMAIN variable through this class. Since, I'm developing application for Android, onCreate() is the first method that invokes. This is my code:
public class MainScreen extends FragmentActivity {
private static final String TAG = "MainScreen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "*********************************");
Log.i(TAG, "Try to run ------- application...");
Log.i(TAG, "*********************************");
// Set Backend mode (Production or UAT)
LinkManager.setBackendMode(1);
...
}
}
Now, when I run the application log shows this output:
06-28 10:00:56.973: I/MainScreen(9014): *********************************
06-28 10:00:56.973: I/MainScreen(9014): Try to run ------- application...
06-28 10:00:56.973: I/MainScreen(9014): *********************************
06-28 10:00:56.973: I/LinkManager(9014): Backend mode: UAT
06-28 10:00:57.023: I/ContentDownloader(9014): Try to open=> nulluser/
Line 4 shows DOMAIN variable has initialized with UAT but after that when other classes invoke methods of LinkManager class DOMAIN contains null. Since DOMAIN is static variable I expect content of this variable should not be changed.
What/where is my mistake?
Any suggestion would be appreciated. Thanks
After you invoke setBackendMode() and before setBackendMode() is really executed, JVM will initialize URL_LOGIN, URL_USER_PROFILE, URL_VENUE_LIST, when DOMAIN is still null.
Solution:
Just do this:
public static String getLoginUrl() {
return DOMAIN + "login/";
}
public static String getUserProfileUrl() {
return DOMAIN + "user/";
}
public static String getVenueListUrl(String lat, String lng, String radius) {
String str = DOMAIN + "venues/?centre_lat=###&centre_lon=####&radius=#####";
// ...
}
It is because
private static final String URL_USER_PROFILE = DOMAIN + "user/";
Is executed before DOMAIN is set in setBackendMode()

Why are there compile errors when accessing an Enum from the main method?

So i'm a little bit confused as i've never used an enum before. I want to use this enum in my main method. For some reason, i can't (i keep getting errors anytime i even try to do Status s; in main). I can however call my TestingEnum method from main and of course this works... but i am 100% sure that using the enum this way is just plain wrong. Could someone tell me how i'd go about using this in main properly?
If i try to do: Status s; in my main method, i get this error - "connot find symbol Status s;"
BACKGROUND: new to java and enums...
class MyClass {
public Status s;
public enum Status {
STATUS_OPEN(1),
STATUS_STARTED(2),
STATUS_INPROGRESS(3),
STATUS_ONHOLD(4),
STATUS_COMPLETED(5),
STATUS_CLOSED(6);
private final int status;
Status(int stat) {
this.status = stat;
}
public int getStatus() {
return this.status;
}
}
private void setStatus(Status stat) {
s = stat;
}
public void TestingEnum() {
Status myStat = Status.STATUS_ONHOLD;
setStatus(myStat);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(NEW_LINE + " Status: " + s + NEW_LINE);
return result.toString();
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
// PROBLEM SETTING STATUS HERE
// I can't do this:
Status s;
}
}
Move the enum to its own class file, or access it with a reference to the enclosing class.
It looks like you defined the Enum as an inner class of another class. If you're doing this, you need to access it with the syntax OuterClass.Status to access it. You made it public, so that will work. You can access it from within the class with no problem because it's contained in the scope of the parent class.
So you can either add the OuterClass. before Status, or you can move the Enum into its own file like any other class.
From the limited code I think the problem is that you try to access
public Status s;
which is not static from the static method main
public static void main(String[] args) {
...
}
Create a instance of your class from main and have a method on that instance use s or declare s as static.
You cannot just instantiate an Enum just before a public class like that. One way to resolve the issues is to have an outer class which will have your Enum class as inner class like this:
public class MyStatus {
static enum Status {
STATUS_OPEN(1),
STATUS_STARTED(2),
STATUS_INPROGRESS(3),
STATUS_ONHOLD(4),
STATUS_COMPLETED(5),
STATUS_CLOSED(6),
ABANDONED(7);
private final int status;
Status(int stat) {
this.status = stat;
}
public int getStatus() {
return this.status;
}
}
private Status s;
public void setStatus(Status stat) {
s = stat;
}
public void TestingEnum() {
Status myStat = Status.ABANDONED;
setStatus(myStat);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(NEW_LINE + " Status: " + s + NEW_LINE);
return result.toString();
}
}
Also ABANDONED wasn't defined so I just added it in the end.
Based on your edit. The problem you have is the name of the class is nested and called MyClass.Status
Try
public static void main(String[] args) {
MyClass obj = new MyClass();
//PROBLEM SETTING STATUS HERE
//I can't do this:
MyClass.Status s = MyClass.Status.STATUS_OPEN;
}
BTW: Your IDE should be able to auto fix this mistake.
The only compilation error I see is that you have used
Status myStat = Status.ABANDONED;
without defining it. I suggest you add this enum or use one you have defined.
I resolved this error by creating a nonstatic enum as outside the class.
public enum Status {
STATUS_OPEN(1),
STATUS_STARTED(2),
STATUS_INPROGRESS(3),
STATUS_ONHOLD(4),
STATUS_COMPLETED(5),
STATUS_CLOSED(6),
ABANDONED(7);
private final int status;
Status(int stat) {
this.status = stat;
}
public int getStatus() {
return this.status;
}
}
Created MyStatus class without inner enum block:
public class MyStatus {
private Status s;
public void setStatus(Status stat) {
s = stat;
}
public void TestingEnum() {
Status myStat = Status.ABANDONED;
setStatus(myStat);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(NEW_LINE + " Status: " + s + NEW_LINE);
return result.toString();
}
}
Resolved for me.
You would not be able to refer to Status in main() because, while Status is public, it is not static. You would need to create an instance of your enclosing class and then use it to create an instance of the enum:
MyEnclosingClass clz = new MyEnclosingClass();
Status status = clz.new Status();
This should resolve the error I believe you are probably getting.

How to find a static String in a Interface

I have the folowing interface;
public static interface Attributes
{
public final static String InterestDeterminationDate = "InterestDeterminationDate";
public final static String CreditType = "CreditType";
public final static String NumberInternal = "NumberInternal";
public final static String InterestRate = "InterestRate";
public final static String RemainingDebtAmount = "RemainingDebtAmount";
public final static String ConsumerPart = "ConsumerPart";
public final static String TechnicalProductName = "TechnicalProductName";
public final static String TermOfDuration = "TermOfDuration";
public final static String PeriodInterestTaxReduction = "PeriodInterestTaxReduction";
public final static String OriginMark = "OriginMark";
public final static String Currency = "Currency";
public final static String PenaltyRuleId = "PenaltyRuleId";
public final static String InstallmentCalculationMethod = "InstallmentCalculationMethod";
public final static String InterestRenewalDate = "InterestRenewalDate";
public final static String TechnicalProductDescription = "TechnicalProductDescription";
public final static String TechnicalProductDate = "TechnicalProductDate";
public final static String CollectionIntervalPeriod = "CollectionIntervalPeriod";
public final static String Enddate = "Enddate";
}
I need to check is a given string is a part of this Attributes Interface.
How can i check this?
Regards,
bas Hendriks
If you really want todo this, then you should use reflection and go through all the values in Attributes.
A better way to do this would be the use of enums :
public enum Attributes{
InterestDeterminationDate,
CreditType,
NumberInternal,
InterestRate,
RemainingDebtAmount,
ConsumerPart,
TechnicalProductName,
TermOfDuration,
PeriodInterestTaxReduction,
OriginMark,
Currency,
PenaltyRuleId,
InstallmentCalculationMethod,
InterestRenewalDate,
TechnicalProductDescription,
TechnicalProductDate,
CollectionIntervalPeriod,
Enddate;
}
and the Attributes.valueOf(yourVariable); would check this for you.
Beware with enum, the valueOf() method will throw a IllegalArgumentException if yourVariable isn't in Attributes. Plus you yourVariable isn't null or you will have to handle a NullPointerException
Your question doesn't make it clear whether you're trying to find out if the query string is the property name or value. If you're trying to find out if it's a value, the following will work:
public static boolean hasValue(String value) throws IllegalAccessException {
for(Field field : Attributes.class.getDeclaredFields()) {
if(((String)field.get(Attributes.class)).equals(value)) {
return true;
}
}
return false;
}
However, I would advise following Colin's suggestion of using an Enum, it will be easier for you to work with in the future.
You can build a set using reflection and test against that set:
Class<Attributes> attr = Attributes.class;
Field[] fields = attr.getDeclaredFields();
final Set<String> fieldsInAttributes = new HashSet<String>();
for (Field field : fields) {
fieldsInAttributes.add(field.getName());
}
System.out.println(fieldsInAttributes.contains("PenaltyRuleId"));
You can use the reflection API, and the "getFields()" method of the Class class.
Then you check the field name with the "getName()" method of the Field class.
Here is the Oracle official tutorial.
public static String getFieldName(String fieldValue) throws Exception {
for (Field field : Attributes.class.getFields())
if (fieldValue.equals(field.get(null)))
return field.getName();
return null;
}

Categories