With IntelliJ 2016.2 is there a way to mark a property/method that should not be included when generation of code is done?
For example this class
public class Person {
private String firstName;
private String lastName;
public void setFirstName(String firstName){ ... }
public String getFirstName() { ... };
public void setLastName(String firstName){ ... }
public String getLastName() { ... };
public String getFullName() { // returns first + last };
}
I would like to mark getFullName so it is not used when generating things like equals or toString since it is merely a connivence function.
This isn't a full answer, but when you generate equals/hashcode, the first screen has an option to select a template. Choose "..." and you can create your own new template for creating equals and hashcode. You might therefore be able to code something, eg reading an annotation on a field, that would allow you to exclude it from the generation.
These look suspiciously like Velocity macros to me but my understanding of them isn't good enough to take the solution any further.
Related
I am trying to use Formatter in webflux application but its throws
java.lang.IllegalStateException: Iterating over a toIterable() /
toStream() is blocking, which is not supported in thread
reactor-http-nio-2
Exception indicate i can't use block and method is expecting an object of PetType. I wanted to know if there is any other way to do this
#Component
public class PetTypeFormatter implements Formatter<PetType> {
private final PetTypeService petTypeServive;
public PetTypeFormatter(PetTypeService petTypeServive) {
this.petTypeServive = petTypeServive;
}
#Override
public String print(PetType petType, Locale locale) {
return petType.getName();
}
#Override
public PetType parse(String text, Locale locale) throws ParseException
{
Iterable<PetType> findPetTypes = petTypeServive.findAll().toIterable();
for (PetType type : findPetTypes)
{
if (type.getName().equals(text)) {
return type;
}
}
throw new ParseException("type not found: " + text, 0);
}
}
Edit:
The method signature of controller which i am using is
#PostMapping("/pets/new")
public String processCreationForm(#ModelAttribute("owner") Owner owner, #Valid Pet pet,BindingResult result, ModelMap model)
and the Pet class petType property which i was setting through the custom formatter when using webmvc
Edit2:
#Setter
#Getter
public class Pet
{
private String id;
private PetType petType;
#DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate birthDate;
private String name;
}
#Setter
#Getter
public class PetType
{
private String name;
#Override
public String toString() {
return name;
}
}
You are trying to implement blocking business logic in a formatter.
The purpose of the Formatter<T> interface is to write custom parsing of strings, for example json strings, csv strings etc. and parse these into an object.
What you are doing is making a database call in a formatter, which is NOT the purpose of the formatter interface.
Since you have not shown us:
the purpose of the formatter
where the formatter is used
whats in the passed string into the formatter
what your request looks like
What a Pet class is
What a PetType is
I can't help you more than this. You are trying to do a blocking call in a webflux application in an interface that does not allow reactive coding (it returns a concrete value), You need to rethink your solution to the problem.
Please explain what your problem is and what it is you want to do, and not the problem with the code, the problem you are trying to solve, and we might be able to help you more.
EclipseLink version is 2.5.1
We've moved from GlassFish web-server to TomCat. This made us switch to static weaving because with TomCat dynamic weaving doesn't really work that easy.
Now that static weaving works, it seems to work quite a bit differently.
If I have an entity which sets some property directly in the constructor:
class Entity {
#Column
private String name;
public Entity() {
name = "something";
}
public String getName() {
return name;
}
}
Long story short this test will fail:
Entity e = new Entity();
assertEquals("something", e.getName()); // e.getName() returns null
This happens because getName(), after weaving, is not returning this.name anymore. Instead it calls a routing for initialization (if it's needed) and (I guess) gets the value of the property from some underlying HashMap.
But constructor is not being weaved, I even have looked into the sources of weaver and seems to be explicitly opting out of this:
/**
* Construct a MethodWeaver and allow it to process the method.
*/
#Override
public MethodVisitor visitMethod(int access, String methodName, String desc, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, methodName, desc, signature, exceptions);
if (!alreadyWeaved) {
// skip constructors, they will not changed
if (!"<init>".equals(methodName) && !"<cinit>".equals(methodName)) {
// remaining modifications to the 'body' of the class are
// delegated to MethodWeaver
mv = new MethodWeaver(this, methodName, desc, mv);
}
}
return mv;
}
The question is, maybe I miss something here? Is it the actual reality with EclipseLink 2.5.1 that you can't use properties directly in entity's own ctor? (and it's not even mentioned anywhere, not googlable at least)
It turns out yes, we can.
But there was a problem that led us to the property being not visible to the getter.
We actually have MappedSuperclass inheritance here and we were shadowing this field in the child class. Essentially this:
class A {
#Column()
protected String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class B extends A {
#Column()
protected String name;
// no #Override here
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
So we were just shadowing the property.
I need to extend a piece of code that writes a paragraph using constant strings defined in an interface:
public class paragraphGenerator implements EnglishParaGraph(){
public StringBuffer outputParagraph = new StringBuffer();
public void generate(){
writeParagraph(PARA1);
//some long and complicated logic here
writeParagraph(PARA2);
//some long and complicated logic here
writeParagraph(PARA3);
}
public void writeParagraph(String content){
//manipulates the paragraph and puts it in stringbuffer
}
}
public interface EnglishParaGraph{
public static final String PARA1 = "Hello";
public static final String PARA2 = "Thank you";
public static final String PARA3 = "Goodbye";
}
Running generate() should write something like "Hello Thank you Goodbye".
Now I want to generate a French equivalent so the output looks something like "Bonjour Merci Salut".
According to Template Method Pattern can overwrite generate() in a subclass and change each writeParagraph's input argument, but that will repeat most of the code which is not desirable.
What's the most suitable design pattern to use here? I was told to use as little replicating code as possible.
The design of the interface and extending class is simply wrong. To be clear, interfaces are specifically used to avoid defining implementation details. The code you posted does the exact opposite of that and defines implementation details using an interface.
At worst, you want to make the interface define something like this:
public interface ParagraphSource{
public String getParagraph1Text();
public String getParagraph2Text();
public String getParagraph3Text();
}
public class EnglishSource extends ParagraphSource {
public String getParagraph1Text() {
return "Hello";
}
public String getParagraph2Text() {
return "Thank you";
}
public String getParagraph3Text() {
return "Goodbye";
}
}
public class FrenchSource extends ParagraphSource {
public String getParagraph1Text() {
return "Bonjour";
}
public String getParagraph2Text() {
return "Merci";
}
public String getParagraph3Text() {
return "Au revoir";
}
}
Then your paragraph generator can use different sources:
public class ParagraphGenerator {
public StringBuffer outputParagraph = new StringBuffer();
public void generate(ParagraphSource source){
writeParagraph(source.getParagraph1Text());
//some long and complicated logic here
writeParagraph(source.getParagraph2Text());
//some long and complicated logic here
writeParagraph(source.getParagraph3Text());
}
}
I am looking at AspectJ to see if perhaps we can use it in our test suite.
We have a rather large third party Java communications library hardwired to use its own classes (which do not implement any interfaces) which in turn mean that we need a physical backend present and correctly configured to be able to run tests.
I am looking at our options for removing this restriction. A possibility would be to create a subclass of the troublesome classes and then ask AspectJ to simply replace "new X" with "new OurSubclassOfX" when loading the third party library, but I am new to AspectJ and from my brief skimming of the documentation this is not a typical use case.
Can AspectJ do this? What would the configuration snippet be?
Yes, this is possible. Let us assume you have a hard-wired class, possibly fetching something from a database, and want to mock it via an aspect:
package de.scrum_master.aop.app;
public class HardWired {
private int id;
private String name;
public HardWired(int id, String name) {
this.id = id;
this.name = name;
}
public void doSomething() {
System.out.println("Fetching values from database");
}
public int getSomething() {
return 11;
}
#Override
public String toString() {
return "HardWired [id=" + id + ", name=" + name + "]";
}
}
Then there is a little driver application using that very class (not an interface):
package de.scrum_master.aop.app;
public class Application {
public static void main(String[] args) {
HardWired hw = new HardWired(999, "My object");
System.out.println(hw);
hw.doSomething();
System.out.println(hw.getSomething());
}
}
The output is as follows:
HardWired [id=999, name=My object]
Fetching values from database
11
Now you define your derived mock class which should replace the original for testing purposes:
package de.scrum_master.aop.mock;
import de.scrum_master.aop.app.HardWired;
public class HardWiredMock extends HardWired {
public HardWiredMock(int id, String name) {
super(id, name);
}
#Override
public void doSomething() {
System.out.println("Mocking database values");
}
#Override
public int getSomething() {
return 22;
}
#Override
public String toString() {
return "Mocked: " + super.toString();
}
}
And finally you define an aspect with a simple pointcut and advice to replace the original value during each constructor call:
package de.scrum_master.aop.aspect;
import de.scrum_master.aop.app.HardWired;
import de.scrum_master.aop.mock.HardWiredMock;
public aspect MockInjector {
HardWired around(int p1, String p2) : call(HardWired.new(int, String)) && args(p1, p2) {
return new HardWiredMock(p1, p2);
}
}
The output changes as desired:
Mocked: HardWired [id=999, name=My object]
Mocking database values
22
You do that once per class and constructor and are fine. In order to generalise the approach you would need joinpoint properties and, depending on how far you want to go, maybe reflection, but this here is pretty straightforward. Enjoy!
I recently started working in Java and was introduced to the wild and crazy world of getters and setters for everything. I hated it at first, but quickly got used to it. Too used to it.
I have been spending a lot of time lately thinking more about class design. One of the things I am trying to do is avoid the trap of doing getters and setters for everything. However, much of the work I do is with entities that are mainly data containers and I am not certain that getters and setters are actually inappropriate in these cases.
Here is a simple example using public properties.
class Space {
public String name;
public String description;
Space(final String name, final String description) {
this.name = name;
this.description = description;
}
}
Here is a simple example using private properties and using getters and setters.
class Space {
private String name;
private String description;
Space(final String name, final String description) {
this.name = name;
this.description = description;
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
public String getDescription() {
return this.description;
}
public void setDescription(final String description) {
this.description = description;
}
}
In these examples, both the name and the description fields should be able to be changed.
I feel like the getter/setter example is more clear and hides the implementation details of what name and description are. It would also allow for validation on set later if needed.
I have read several discussions about getters and setters being evil and/or an anti-pattern, but it really feels like those might not apply to this situation.
Maybe there are some options I have not yet considered. I'm open for suggestions!
The first version (public properties) is not a good idea. The second is better. As Josh Bloch would say, "favor immutability":
public class Space {
private final String name;
private final String description;
public Space(final String name, final String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
}
That being said, getters and setters tend to be overused.
You have heard the often oversimplified "get/setters are evil". Nobody (I hope) really means that there's anything wrong with it for data objects. I think the real idea is:
"Getters/Setters are evil, except for plain data storage objects" which itself is just an evangelism of "tell don't ask".
Ideally if a class has getters and setters, that's all it should have.
That's the argument anyway. I'm not sure I agree with it.
To put it simple:
You need getters for all fields that must be read from the outside.
You need setters for all fields that must be written from the outside.
This can be 100%, but most of the time it is less.
While the accessor pattern helps hide the implementation details of a class (e.g. using a hashtable to store attributes to save memory on sparsely used classes), it can be very verbose to implement (your example has 12 lines more with accessors). That's why C# has a special property syntax, which allows to concisely specify default accessors:
class Space {
public String Name { get; set; }
public String Description { get; set; }
Space(final String name, final String description) {
this.Name = name;
this.Description = description;
}
}
Alternative forms may add access specifiers and/or code:
private String _name;
public String Name {
get { if (_name == null) FetchName(); return _name; }
private set { _name = value; }
}