how to create java file programmatically - java

I am creating a util-class which writes .java Files that act as coverter - generator.
This util-class will generate AConverter.java' (refer below sample)
I want know how to write the util-class.
I googled, and found the recommendation to use apache bcel. But I couldn't find an example to write the .java File from a String and have it working in my program.
The expectation is...
class ADTO
{
private String empId;
private String empName;
private String dept;
//setters and getters
}
class ABO
{
private String loginId;
private String userName;
private String group;
//setter and getter
}
class AConverter
{
public void doConvertFromDB(ADTO source, ABO dest)
{
dest.setLoginId(source.getEmpId());
...
}
public void doConvertFromBO(ABO source, ADTO dest)
{
dest.setEmpId(source.getLoginId());
...
public ADTO getSourceClass()
{
return ADTO.class;
}
public ABO getDestClass()
{
return ABO.class;
}
}
The above class AConverter will generated by the new Util-class.

You would almost certainly benefit from trying to do this a different way, the number of ways this scheme could fail is worryingly large. Here are some suggestions:
Add a caster method of some sort:
class ADTO
{
private String empId;
private String empName;
private String dept;
// setters and getters
public ABO toABO() // caster method (ABO will need a toADTO() as well)
{
ABO a = new ABO();
a.setSomething(getSomethingEquivalent());
...
return a;
}
}
A proxy class, perhaps a subclass of the intended class. You would need 2, one derived from each class.
class ADTO_Proxy extends ADTO
{
private ABO abo;
public ADTO_Proxy(ABO a)
{
super();
abo = a;
}
#override
public String getEmployeeId()
{
return abo.getLoginId();
}
// other setters and getters
}
Rather than trying to make an adapter, merge the classes. Could be easily accomplished with the following:
class ADTO
{
private String empId;
private String empName;
private String dept;
// getters and setters for each variable by each name
public String getEmployeeId()
{ return empId; }
public String getLoginId()
{ return empId; }
public String getEmployeeName()
{ return empName; }
public String getUsername()
{ return empName; }
public String getDepartment()
{ return dept; }
public String getGroup()
{ return dept; }
// setters
}
This could also be done with interfaces.
HateYourselfLaterâ„¢ Ratings:
The first method ranks a 2, the best of the three. Rating earned because you won't ever find yourself accidentally switching between the two and not much other code has to be changed.
The second method ranks a -3, in the middle of the three. Rating earned because you may occasionally mix up objects that are of one type of the other, with possible unintended side effects. You can reduce this to a rating of 0 if you omit setters from the proxy classes, but this limits functionality.
The third method gets a -5, the worst of the three. Rating earned because there is a lot of possibility for side effects and the redundant code will probably trip you up later. However, you can make rate 1 by refactoring everything to properly use only one class, but that might take a lot of work, and you'll hate yourself for it now.
That said, your original idea of generating a class on the fly to convert between the two ranks about a -10 because it will be horribly difficult to maintain and very sensitive to any changes of the underlying classes, and will probably be easy to break.
HateYourselfLaterâ„¢ Scale ranges from -10 to 10, with 10 being the largest amount of like, and -10 being the largest amount of hate.
Original Answer:
You want a decompiler. There are several java decompilers available to pick from, I'll list a few:
Showmycode - easy to use, decent decompiling, online (thus unsuitable for corporate material), screws up built in class names and nested anonymous classes
Jad - downloadable, CLI, works but produces ugly code, linux version is out of date (use windows version with wine if necessary) , screws up enums, foreach loops, and some try/catches
Fernflower - CLI, hard to find, best output of the three, author is SO user, decent looking output, screws up try/catches sometimes
None of them are perfect, but that's just a result of the fact that some data gets lost during compilation, and decompilers must guess what the program originally looked like.

You can do multiple things.
You SHOULD decide what you want to do precisely and then get a matching library do it for you and learn that library.
BCEL is one such library. I've used Java-APT in the past successfully for similar purposes.
For your understanding I will write some things about generating classes below, but please, don't develop this yourself, you most likely will end up stuck.
If you want to have your class available within the same JVM you are currently running (in opposition to: you want to generate code and then compile the whole program again and restart it) then you have to:
Create the File, write your String to it.
Compile the File (a rough way to do so would call javac from the code)
load the classes into your classloader.

Related

Is it possible to build an object like this at runtime in java?

As the title says....
I want to build a POJO with four field variables and at certain runtime events create an instance of this POJO with access to possibly maybe two or three of the fields.
public class Category implements Serializable {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Lets say I create a new Category object but I only want to be able to have access to the name field during runtime. Is there a design pattern I can use to achieve this? I thought about the strategy pattern and looked at the builder but I am still confused if I can do this in java.
Basically the overall goal is to grab an object from a database and return it as a JSON response in jax rs. But sometimes I dont want a complete object returned but only lets say halve of the object to be accessible at during certain runtime events. My apologies if this seems like a dumb question but I know what I want to do but just don't know the best way.
I have the same problem with you, and my project was used springmvc,and the json tool is jackson.With the problem solved, I just use #JsonIgnore.For more details,just read jackson-how-to-prevent-field-serialization
So someone correct me if I am wrong or see a better option than this...with alot of objects this can be alot of extra code for serialization and deserialization...Jackson Provisions is what I need. I can use the annotation #JsonView(DummyClass.class) on the field variable. I will accept this a the best answer in a day or two unless someone else posts a better response.
// View definitions:
class Views {
static class Public { }
static class ExtendedPublic extends PublicView { }
static class Internal extends ExtendedPublicView { }
}
public class Bean {
// Name is public
#JsonView(Views.Public.class) String name;
// Address semi-public
#JsonView(Views.ExtendPublic.class) Address address;
// SSN only for internal usage
#JsonView(Views.Internal.class) SocialSecNumber ssn;
}
With such view definitions, serialization would be done like so:
// short-cut:
objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);
// or fully exploded:
objectMapper.getSerializationConfig().setSerializationView(Views.Public.class);
// (note: can also pre-construct config object with 'mapper.copySerializationConfig'; reuse)
objectMapper.writeValue(out, beanInstance); // will use active view set via Config
// or, starting with 1.5, more convenient (ObjectWriter is reusable too)
objectMapper.viewWriter(ViewsPublic.class).writeValue(out, beanInstance);
This information was pulled from http://wiki.fasterxml.com/JacksonJsonViews
with jackson 2.3, I can do this with JAX-RS
public class Resource {
#JsonView(Views.Public.class)
#GET
#Produces(MediaType.APPLICATION_JSON )
public List<Object> getElements() {
...
return someResultList;
}
}

GWT: how to format number on server and client (Gin/Guice)

In my GWT + App Engine project, I have a function that formats a double into a String that I need to use on the client and server side.
As you cannot use DecimalFormat in GWT, you have to use NumberFormat on the client-side, and DecimalFormat on the server-side.
I have a class that is used on both sides of the wire (UnitRate) which needs to use this function, so I implemented two classes: ClientUtilities and ServerUtilities which both implement the Utilities interface like so:
public interface Utilities extends Serializable
{
public String formatUnitOnePlace(Double value);
}
public class ClientUtilities implements Utilities
{
#Override
public String formatUnitOnePlace(Double value)
{
NumberFormat fmt = NumberFormat.getFormat("#0.0");
return fmt.format(value);
}
}
public class ServerUtilities implements Utilities
{
#Override
public String formatUnitOnePlace(Double value)
{
DecimalFormat oneDigit = new DecimalFormat("#0.0");// format to 1 decimal place
return oneDigit.format(value);
}
}
The initial idea was to bind the classes using Gin/Guice and inject Utilities into the UnitRate class so that the right implementation gets used depending which side of the wire we are on. UnitRate can be a child of Offer (server-side) and OfferDto (client-side), but this is seeming like a rather long-winded way to do it as the UnitRate entities need to be created by hand, and the only way to do it I have managed is using Assisted Injection.
This however which is creating a ripple effect through the program meaning that more and more of my domain model has dependencies so need to be created by Gin/Guice which is obviously not ideal.
See usage here:
public class UnitRate implements Serializable, HasUnitType, Comparable<HasUnitType>, HasTotal
{
// omitted for brevity
private Utilities utilities;
#AssistedInject
private UnitRate(#Assisted UnitType unitType, Utilities utilities)
{
this.unitType = unitType;
this.price = "";
this.utilities = utilities;
}
#Override
public String getTotal()
{
// some calculations first...
return utilities.formatUnitOnePlace(result);
}
}
I'm not sure what the ideal solution for this would be...
I could go the route of not using DecimalFormat and NumberFormat altogether and implementing some kind of math-based solution, but I'd rather not.
I could split UnitRate into UnitRate and UnitRateDto but I don't see the point - they are never stored in the datastore and only ever exist as child entities of another.
How do I solve this problem? WHY, GWT, WHY?
(I'd just like to add that this is highly simplified. In reality there are other formatting things the Utilities interface needs to do, and other places it needs to be used/injected.)
You may be able to get this working by using the #GwtIncompatible for the method where you are trying to retrieve the DecimalFormat class. This notifies the compiler to ignore this method and or class. Take a look at com.google.gwt.core.shared.GwtIncompatible for more info on how the annotation works.
Let me know if this solves your issue.
This might solve your issue btw.
#GwtIncompatible
public class ServerUtilities implements Utilities
{
#Override
public String formatUnitOnePlace(Double value)
{
DecimalFormat oneDigit = new DecimalFormat("#0.0");// format to 1 decimal place
return oneDigit.format(value);
}
}

Generate Getters and setters without underscore (not prefix/suffix) + eclipse

My variable is
private String category_code = null;
My getter and setter is generated as
public String getCategory_code() {
return category_code;
}
public void setCategory_code(String category_code) {
this.category_code = category_code;
}
Is it possible to generate
public String getCategorycode() {
return category_code;
}
public void setCategorycode(String categorycode) {
this.category_code = category_code;
}
I checked Properties-->Code Style-->Fields but that is only for prefix and suffix.
Or should I just rename my variables as m_categoryCode? and get my output as follows?
public String getCategoryCode() {
return m_categoryCode;
}
public void setCategoryCode(String categoryCode) {
m_categoryCode = categoryCode;
}
Which is better?
The names of the getter and setter methods are derived from the field name. If you use a prefix or suffix for fields (e.g. fValue, _value, val_m), you can specify the suffixes and prefixes in the Code Style preference page (Windows > Preferences > Java > Code Style).
reference at here
Java code tends to follow the camelCaseStyle, not the c_underscore_style. Following the existing standards will generally help you in a variety of ways (you will be able to better read others' code and others will be able to better read your code, where "others" are other developers in the same language). also, the tooling for the language tends to work better (case in point).

Is simulating structs in Java a good way to go or not? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Once I worked for a big tech company. We programed in Java. Guys there are amazingly smart and they like simulating struct in C/C++ in Java. To make myself clear, they advocate to create classes that act as "data holder":
public class BookInformation {
public final List<String> authors;
public final String bookTitle;
public BookInformation(List<String> authors, String bookTitle) {
this.authors = authors;
this.bookTitle = bookTitle;
}
#Override
public String toString() { ... }
#Override
public int hashCode() { ... }
#Override
public boolean equals(Object obj) { ... }
}
As we can see, the purpose of this class is simply holding data. Although we violate many enterprise programming rules, such as not exposing class fields directly and defensive copying, this kind of class does gain benefits such as concise coding. Instead of calling getters and setters, we can directly call field names.
The thing that annoys me is that this kind of class is hard to maintain and extend. It is hard to maintain because there is no way to make sure the states of the objects are legal. Business logic may say, a book must have a title and at least one author. But in real world, the objects can have empty title, null title, empty author list or null author list and we simply cannot control it. It is hard to extend. For example, what if the data source is changed to provide first name, last name separately for author name? I have to use two string lists instead of one. Worse, the data structure change affects and interface. Since I don't have a getAuthorNames() interface, I potentially have to change codes in many places.
I have to admit that the above scenarios are not happening. I have to admit that all code uses the class is under the control of the team so interface change doesn't sound that bad as writing for other teams/companies to use. So is it OK to have such coding standard even if we are using Java, a pure OO language, coding in enterprise level?
I know there probably isn't a "right" answer. I'd like to hear personal opinions. Speak loud on behalf of yourself!
EDIT:
OK. I should rephrase the core of my question: is it wise to sacrifice some of the textbook coding rules to gain simplicity? Will the sacrifice bit you later when the code base grows and team grows? Personal opinions matter, especially it is from wise persons and in many cases, there isn't right or wrong questions and we all just follow the convincing opinions. I am sorry Stackoverflow is designed only for right-and-wrong questions. In that case this question should just be closed.
I think there's a right answer: If it works for you, go for it. There are no style cops waiting to arrest you.
Know the rules and the reasons behind them. When you break them, understand the consequences. Have good justifications for what you do. Live with what happens.
For example, I don't think the rule to never expose data in public need be absolute - as long as you do it properly.
You need to realize that you did it wrong.
The fact that you made that List reference final just means that the reference can't be changed. The List that the reference refers to can have elements added and removed. You have to make it immutable to achieve what you want.
If you don't make it immutable, the changes you make to the reference you pass into the constructor will be reflected in your object. This would be true even if you made that reference private. You have to make a copy of the List you pass in to make your object's state truly independent. Same with other references to mutable types, like Date.
It works with String because it's immutable.
One more thing: that should be equals(), not Equals(). Case matters in Java.
public final class BookInformation {
public final List<String> authors;
public final String bookTitle;
public final Date publicationDate;
public BookInformation(List<String> authors, String bookTitle, Date publicationDate) {
this.authors = Collections.unmodifiableList((authors == null) ? new ArrayList<String>() : authors);
this.bookTitle = (StringUtils.isBlank(bookTitle) ? "" : bookTitle);
this.publicationDate = ((publicationDate == null) ? new Date() : new Date(publicationDate.getTime()));
}
#Override
public String toString() { ... }
#Override
public int hashCode() { ... }
#Override
public boolean equals(Object obj) { ... }
}
I find the standard getter/setters to be needlessly verbose sometimes but there are ways around this.
For example, you can use a getter or setters which is the same name as the fields and you can create operation methods which are more concise than accessing the fields directly.
e.g.
public class BookInformation {
private final Set<String> authors = new LinkedHashSet<>();
private final String bookTitle;
public BookInformation(List<String> authors, String bookTitle) {
assert authors != null;
assert bookTitle != null;
for(String author: authors) addAuthor(author);
this.bookTitle = bookTitle;
}
public String bookTitle() { return bookTitle; }
// get all the authors without needing a defensive copy.
// for(int i = 0, len = bookInfo.authorCount(); i < len; i++) {
// String name = bookInfo.author(i);
public int authorCount() { return authors.size(); }
public String author(int n) { return authors.get(n); }
public void addAuthor(String name) {
assert name != null
authors.add(name);
}
class AuthorCounter {
private final ConcurrentMap<String, AtomicInteger> authorCountMap =
new ConcurrentHashMap<>();
public void addAuthor(String name) {
authorCountMap.putIfAbsent(name, new AtomicInteger());
}
public void incrCountFor(String name) {
authorCountMap.get(name).incrementAndGet();
}
public int countForAuthor(String name) {
AtomicInteger ai = authorCountMap.get(name);
return ai == null ? 0 : ai.get();
}
}

Return two values from a java method

Let's say I have a method in java, which looks up a user in a database and returns their address and the team they are on.
I want to return both values from the method, and don't want to split the method in two because it involves a database call and splitting involves twice the number of calls.
Given typical concerns in a moderate to large software project, what's the best option?
whatGoesHere getUserInfo(String name) {
// query the DB
}
I know the question smells of duplication with existing ones, but each other question had some element that made it different enough from this example that I thought it was worth asking again.
you have some options.
The most OOP it will be create a class to encapsulate those 2 properties, something like that
private class UserInfo {
private Address address;
private Team team;
}
Or if you want a simple solution you can return an array of objects:
Object[] getUserInfo(String name) {
// query the DB
return new Object[]{address,team};
}
Or if you want to expose this method to some library you can have some interface that it will consume those properties, something like this:
class APIClass{
interface UserInfo{
public Address getAddress();
public Team getTeam();
}
UserInfo getUserInfo(String name) {
// query the DB
return new UserInfo(){
public Address getAddress(){ return address; }
public Team getTeam(){ return team; }
};
}
}
cant a map help , A MultivalueMap. Where the key is the user name and the 2 values are the adress and the team name. I am assuming both your Address and team are String variables, You can know more about Multivalue Map here
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiValueMap.html
http://apachecommonstipsandtricks.blogspot.in/2009/01/multi-value-map-values-are-list.html
First model your abstractions, relationships and multiplicity well (see an e.g. below). Then you can model tables accordingly. Once these two steps are performed you can either leverage JPA that can be configured to load your object graph or you write JDBC code and create the graph your self by running a SQL query with proper SQL JOINs.
A User has an Address
A Team can have 1 or more Users (and can a User play for more teams?)
You can return a String array with user name and group name in it . The method looks like :
public String[] getUserInfo(String name) {
String[] result = new String[2];
// query the DB
...
result[0] = userName;
result[1] = groupName;
return result;
}
A common solution to this kind of issue is to create a custom object with as many attributes as the values you want to return.
If you can't create a new class for this, you can use a Map<String, Object>, but this approach is not type-safe.
I thought Guava had a generic Pair class already, but I cannot find it. You can build your own using generics if you're on Java 1.5+.
public class Pair<X,Y>
{
public final X first;
public final Y second;
public Pair(X first, Y second) {
this.first = first;
this.second = second;
}
}
Feel free to make the fields private and add getters. :) Using it is easy:
return new Pair<Address,Team>(address, team);
Update
Apache Commons Lang has Pair. See this SO question for more options.

Categories