Create a constructor which use another class - java

I try to create a template object of task using existing task object. When i use a special constructor I get the error:
incompatible types: Task cannot be converted to TaskTemplate
Here is the code I'm using the create the TaskTemplate:
TaskTemplate bean = new TaskTemplate(newTask);
Here is the constructor I'm calling:
public TaskTemplate(Task task) {
this.setTitle(task.getTitle());
this.setDate(task.getDate());
}
But when I set all properties in the place where object is created everything is ok.
TaskTemplate bean = new TaskTemplate();
bean.setTitle(newTask.getTitle());
bean.setDate(newTask.getDate());
Why does it happen?
How can I create a constructor which will get a task and create a template?

It is highly likely that you need to rebuild your project.
This kind of problem can happen when the compiled class the calling code is using is out of date with the source code you are viewing, causing great consternation when recent changes (such as creating a new constructor) do not seem to exist from the perspective of the calling code.
Most IDEs automatically rebuild as you code: Check that your IDE is configured to build automatically. If you aren't using an IDE, consider using one.

Related

Create custom gradle plugin to analyze java source code and generate codes

I am trying to create a plugin to generate some java code and write back to the main source module. I was able to create a some simple pojo class using JavaPoet and write to the src/main/java.
To make this useful, it should read the code from src/maim/java folder and analyze the classes using reflection. Look for some annotation then generate some codes. Do I use the SourceTask for this case. Looked like I can only access the classes by the files. Is that possible to read the java classes as the class and using reflection analyze the class?
Since you specified what you want to do:
You'll need to implement an annotation processor. This has absolutely nothing to do with gradle, and a gradle plugin is actually the wrong way to go about this. Please look into Java Annotation Processor and come back with more questions if any come up.
With JavaForger you can read input classes and generate sourcecode based on that. It also provides an API to insert it into existing classes or create new classes based on the input file. In contrast to JavaPoet, JavaForger has a clear separation between code to be generated and settings on where and how to insert it. An example of a template for a pojo can look like this:
public class ${class.name}Data {
<#list fields as field>
private ${field.type} ${field.name};
</#list>
<#list fields as field>
public ${field.type} ${field.getter}() {
return ${field.name};
}
public void ${field.setter}(${field.type} ${field.name}) {
this.${field.name} = ${field.name};
}
</#list>
}
The example below uses a template called "myTemplate.javat" and adds some extra settings like creating the file if it does not exist and changing the path where the file will be created from */path/* to */pathToDto/*. The the path to the input class is given to read the class name and fields and more.
JavaForgerConfiguration config = JavaForgerConfiguration.builder()
.withTemplate("myTemplate.javat")
.withCreateFileIfNotExists(true)
.withMergeClassProvider(ClassProvider.fromInputClass(s -> s.replace("path", "pathToPojo")))
.build();
JavaForger.execute(config, "MyProject/path/inputFile.java");
If you are looking for a framework that allows changing the code more programatticaly you can also look at JavaParser. With this framework you can construct an abstract syntax tree from a java class and make changes to it.

Eclipse Groovy DSLDs and static compilation

Is it possible to define Eclipse Groovy DSLD (DSL Definition) which can be statically compilable?
I tried to use DSLD example provided by Eclipse, so I created TestDsl.dsld:
contribute(currentType(subType('groovy.lang.GroovyObject'))) {
property (
name : 'newProp',
type : String,
provider : 'Sample DSL',
doc : 'This is a sample. You should see this in content assist for GroovyObjects: <pre>newProp</pre>')
}
Then I wrote a test class using previous property. This class should be compiled statically. Eclipse is showing new property as a valid one, but then it fails to compile.
Same result occurs using both #CompileStatic and #TypeChecked.
DSLDs introduce new methods and properties into content assist and type inferencing. This does not guarantee the methods or properties will be available at compile- or run-time. They operate more like hints than anything.
Quite often, DSLDs are used to fill a gap that exists between the static type checker and the dynamic execution state of your program. If you want something that is compatible with #TypeChecked or #CompileStatic, you may need to write a TypeChekingExtension instead of a DSLD contribution.

POI for XPages - using xwpfdocument

To help solve another problem I have, I'm testing the following code in the postGenerationProcess event of the POI Word widget:
var jce:writeXWPFDocument = new writeXWPFDocument();
var newString3 = jce.doSomething3(xwpfdocument);
print("newString3 = " + newString3);
doSomething3 is defined in a Java class contained in the .nsf.
public class writeXWPFDocument {
public String doSomething3(XWPFDocument xwpfdocument) {
return "DO SOMETHING - xwpfdocument";
}}
When I run this code, I get the error:
Java method 'doSomething3(org.apache.poi.xwpf.usermodel.XWPFDocument)'
on java class 'AZGPackage.writeXWPFDocument' not found
What could be causing this error?
#Knut Hermann - this is a test which relates to the other problem you have been helping me with.
Edit to make the correct answer easier to find:
I have used poi in a few applications. I've encountered similar problems twice: First, usually when I accidentally import a class with the same name from the wrong package (like lotus.local.domino.Database instead of lotus.domino.Database). The other time I encountered this (and the only time the package name was identical) was when I had poi in a plug-in that I had added to the build path and also had it installed by a poi extension library I had built. If you can't cast an object as itself, there is an issue with the ClassLoader, and I don't know what would cause that other than a class being listed twice.
SSJS seems to pass a different object type to the function. Try to change the class of the parameter to Object and for testing return the class name.
In a production code you could check with instanceof if the parameter has the right data type.
In General: consider using a facade pattern, so you keep your complex Java classes away from SSJS

IllegalArgumentException when using SpinnerItem in SmartGWT

I am trying to use a SpinnerItem as the editor type for a ListGridField
final ListGridField quantityGridField = new ListGridField("quantity", "Cantidad");
quantityGridField.setEditorType(SpinnerItem.class);
quantityGridField.setCanEdit(true);
But after I compile the project and deploy it this error comes up.
java.lang.IllegalArgumentException: No BeanFactory has been registered for: com.smartgwt.client.widgets.form.fields.SpinnerItem
This is the first time that I get this error and I have not found any related question here.
As it's described in javadoc to the method that you use (setEditorType(class)) you use Reflection mechanism of smartgwt. You can read about it here: http://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/docs/Reflection.html .
According to this documentation you should register SpinnerItem(which is a subclass of FormItem) prior of using it:
Similarly, to register FormItem and all its subclasses found in the
classpath (including your custom subclasses), you can use the
BeanFactory.FormItemMetaFactory.
GWT.create(BeanFactory.FormItemMetaFactory.class);
So just try to insert this GWT.create line somewhere in your code before using it, so gwt compiler will be able to find your editor.

How can I create an auto-generated enum from a resource file?

I want to create an auto-generated resource file similar to R from android. I know how to do the parsing and creation of the file and essentially creating a new class file. What I don't know how to do is start this auto-generation process.
So, using eclipse (although if there is a way to make this happen in an agnostic fashion, I would prefer it), how can I trigger an auto-generation session to read a properties file and create a .java file holding static variables and the "keys" from this parsed file, that I can then reference from my code?
A few examples of how to generate java source files have already been provided. It should be relatively easy to read the properties file and invoke one of these APIs.
To trigger the code generation process, you need to add a custom build step. With Ant, just add a custom task. And then hook it up to an Eclipse Builder: project Properties -> Builders -> New.
Subsequently, Eclipse should find and refresh this file on its own. If it doesn't, then check your configs: Preferences -> General -> Workspace -> find "Refresh using native hooks or polling" and similar ones and check them. (Note that I'm not 100% sure that this last part will work.)
The path of least resistance is to run this build step separately. If your properties file is not changing that often, then it shouldn't be that big a deal. This is similar to what you'd do if you use Protocol Buffers, JAXB, wsdl2java, etc. If you want everything to work magically like R.java does, then you probably have to do something a little more complicated:
 - Try to use Eclipse Builder options to control when the Ant task is executed
- If you can't figure that out, then I'd check out how Eclipse hooks up to the above projects (that is, to Protocol Buffers, JAXB, wsdl2java, etc.)
- Look at the ADT custom PreCompilerBuilder class
- Check out the build-helper-plugin
It is common to use a ResourceBundle to create an object that allows you to lookup properties by key. You can learn about the ResourceBundle on the Java Trail.
The basic idea is that you have a text file with a .properties extension. You point the ResourceBundle object to that file. You can then use the getString() or getObject() method passing in the key to the property you want. That is all there is to it. You just need to load the ResourceBundle when you start your program (or sometime before you need it).
If you create you own class that has a ResourceBundle as a member value, you can use a simple bit of code like this to have a simple get() method to get the property value:
public String get(String aString)
{
String sVal = null;
try
{
sVal = (String)myProperties.getObject(aString);
}
catch (MissingResourceException e)
{
log.debug("Missing Property Value: "+aString);
}
return sVal;
}
I hope that is useful.

Categories

Resources