How to add extra code into main java method? - java

I want to add a sentence to all new classes that I create in java. By default Java entry point comes like this:
public static void main(String[] args) {
}
and I want to achive something like this:
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
}
Is this possible? Thank you!
Eclipse Java EE IDE for Web Developers.
Version: Mars Release (4.5.0)
Build id: 20150621-1200

You can create/edit/ any code template you want
For Eclipse go to
Window
Preferences
Java
Editor
Templates
More here:
http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fpreferences%2Fjava%2Feditor%2Fref-preferences-templates.htm
another here :
http://help.eclipse.org/mars/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2FgettingStarted%2Fqs-EditorTemplates.htm

In Eclipse it is possible to edit built-in code templates (the one used by Eclipse e.g. for new class files) and create your own named snippets (for fast access to often-reused templates).
Code Templates
Go to Window > Preferences > Java > Code Style > Code Templates, then to Code > New Java files. Adapt this or some other template to suit your needs.
Templates
Usually it's better though to add a smaller template via Window > Preferences > Java > Editor > Templates and use it wherever you need. Smaller bricks are more reusable then hardcoded class templates. Those are applied with <type-beginning-of-template-name + ctrl + space.

Related

Template based - Code generator framework or tool

Summary
Based on the template need to generate a code, Output needs to be a Java/DotNet code
Analyses
Using the yeoman (https://yeoman.io/generators/). Created a Java ->
Hello World code generator.
Which takes the string as input and map that in the sysout.
Code
class HelloWorld {
public static void main(String args[]){
System.out.println("Hello World");
}
}
Yeoman template code
Template folder contains --> <className>Class.java.ejs
Input Args--> <className> , <message>
Input value --> HelloWorld, Welcome
class <%= className%>Class {
public static void main(String args[]){
System.out.println(<%= "message"%> );
}
}
Output:
HelloWorldClass.java
Based on the inputs, Values will map in the template and finally. I will get className.java class.
Expected
For the template based code generator Found "yeoman" framework uses development language as node.js. Its pretty good.
Like this any other template based code generator framework available in Python or node or js?
You should take a look at code generators based on template files.
For example Telosys which is based on the Velocity template engine.
It is quite simple and easy to use. And above all it can generate any type of language.
See templates examples for Java :
https://github.com/telosys-templates-v3/java-domain-T300
you can use ANTLR 4 along with StringTemplate or Velocity template to achieve this.
ANTLR would take care of your parsing part and you can use the generated string from ANTLR in your template for substitution.

Eclipse - how to create on-class-created template

I watched the question about Eclipse -> Java -> Templates and how to create template to decrease code time development but I couldn't find how to:
generate template on Java class created
generate the template for some special Java classes which extend javax.swing.JPanel
for example how to generate code like :
public class AClass extends JPanel {
public AClass(){this.aMethod();}
private void aMethod(){}
}
...on Java class created?
EDIT :
I try to invoke template code generation on new java source file created (see image)
I tried to edit the preferences -> Java -> code templates constructor body (see image) but I am not sure how to insert method invoke into constructor body :(
I tried to input this.aMethod(); into the edit text area but this doesn't generate constructor body as : public AClass(){this.aMethod();}
for question A :
You can edit template through eclipse preferences :
Java code style > Code template
For question B :
You would have to create a custom new file wizard (a little overkill maybe...)
you can find a simple tutorial on vogella :
http://www.vogella.com/tutorials/EclipseWizards/article.html

Creating a new Java project

I am able to create a default project in PDE just like mentioned here.
However I want to know how to create a Java project. How can I do that?
As a minimum you need to add the Java project nature to the project you create. Use something like:
private void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException
{
IProjectDescription description = proj.getDescription();
String[] prevNatures = description.getNatureIds();
String[] newNatures = new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length] = natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
The nature id for a Java project is 'org.eclipse.jdt.core.javanature' (also in the JavaCore.NATURE_ID constant).
Note that this does not add the various builders that are normally used in a Java project. The IProjectDescription.setBuildSpec method adds those in a similar way. Create a command for the build spec with:
ICommand command = description.newCommand();
command.setBuilderName(builderID);
where 'builderId' is 'org.eclipse.jdt.core.javabuilder' for the main Java builder (JavaCore.BUILDER_ID constant).
All this information is stored in the '.project' file in the project root folder. This is an XML file which you can look at to see the set up of existing projects.
Window->Open Perspective->Java
then
File->New->Java Project (you may have to go via "Project..." to get to the "Java Project" option)
Please refer to New Project Creation Wizards
On the Plug-in Project page, use com.example.helloworld as the name
for your project and check the box for Create a Java project (this
should be the default). Leave the other settings on the page with
their default settings and then click Next to accept the default
plug-in project structure.

How to do code format switching in eclipse?

A)
public class SomeClass
{
private SomeClass()
{
}
public String someMethod()
{
return "";
}
}
B)
public class SomeOtherClass{
private SomeOtherClass(){
}
public String someOtherMethod(){
return "";
}
}
I have joined a new team and will be working on a project which follows the A) convention. However, I have always been the B) java style person and am way more comfortable with B).
1)On the checked out code, is there a way I could convert the java code style in my eclipse to B)
2)And also ensure the project->Team->Synch with Repo ignores this style change when checking for updates ?
3)Before comitting, I want to switch the code back to the commonly followed style and check it in. I synch for changes every morning and commit changes throughout the day.
Is creating a new profile in the preferences->code style->Formatter the only way ? I also looked at http://astyle.sourceforge.net/ but I am somehow confident there is a simpler eclipse solution to this. How could I achieve this in the simplest possible way ?
I am using eclipse kepler
Work flow:
In Windows > Preferences > Java > Editors Save Actions deselect formatting on save.
Check out code.
Clean up your code(Right click on project go to Source > Clean up. Note this works on project level but not on working set, so you have to do it on each and every project) with your Formatter(B) profile enabled.
In Windows > Preferences > Java > Editors Save Actions select formatting on save and start working.
Same as step 1.
Same as 3 but with formatter profile A.
Commit the code.
These steps can be automated with Ant/Maven script(?) or by developing your own eclipse plug-in.
On sync comparator will NOT ignore style change. IMHO there is no escape. Clean up before sync is only the go.
In Git SCM there are some commit and checkout hooks but I haven't explored on this.

What is the Eclipse equivalent of IntelliJ "Live templates"?

I mean stuff like typing "iter" and getting a "for" loop with a choice of what variable to iterate on , typing "soutv" to generate a "System.out.println" with the "variable=" already in ...
Thanks !
It is called Templates and it's found under,
Window → Preferences → Java → Editor → Templates
The "soutv" template does not exist ("sysout" does, and it's similar), but it's easy to add. I used this pattern:
System.out.println("variable=" + ${cursor}${});
For 'soutv' particularly, I found the following pattern worked well in Eclipse:
System.out.println("${var} = ${cursor}" + ${var});
As others have mentioned, you can add this template by navigating to Window > Preferences > Java > Editor > Templates and clicking New.
The equivalent of 'iter' seems to be 'for' in Eclipse.
Check under
Window -> Preferences -> Java -> Editor -> Templates
Reference:
Template Variables
They are called Templates.
Go to Preferences > Java > Editor > Templates to see a list of pre-defined templates.
For example, sysout is:
System.out.println(${word_selection}${});${cursor}
You can also create your own.

Categories