how to pass object parameters in command?

use of command line arguments in java
java command line arguments file input
how to pass arguments to main method in java using command line
java command line arguments parser
how to pass arguments to main method in java using eclipse
java command line arguments key value
command line arguments in java eclipse
java command-line options

I created an eclipse-rcp's project's plugin.xml with a new command with a parameter.

 ArrayList<parameterization> parameters = new ArrayList<parameterization>();
 IParameter iparam;

 //get the command from plugin.xml
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
 ICommandService cmdService =     (ICommandService)window.getService(ICommandService.class);
 Command cmd = cmdService.getCommand("org.ipiel.demo.commands.click");

//get the parameter
iparam = cmd.getParameter("org.ipiel.demo.commands.click.paramenter1");
Parameterization params = new Parameterization(iparam, "commandValue");
parameters.add(params);

//build the parameterized command
 ParameterizedCommand pc = new ParameterizedCommand(cmd, parameters.toArray(new       Parameterization[parameters.size()]));

//execute the command
 IHandlerService handlerService = (IHandlerService)window.getService(IHandlerService.class);
handlerService.executeCommand(pc, null);

I tried this example to pass parameters and it worked.

The issue in this example that I could pass only parameters of type String. ( because Parameterization )

I want to pass parameter of hash map and in general to pass any object.

I tried this code

     IServiceLocator serviceLocator = PlatformUI.getWorkbench();
    ICommandService commandService = (ICommandService)      serviceLocator.getService(ICommandService.class);




    ExecutionEvent executionEvent = new ExecutionEvent(cmd, paramArray, null, null);
    cmd.executeWithChecks(executionEvent);

but it didn't work the parameters didn't move ( it was null)

Could you please help to to move object as parameter in command ?

Since it would get confusing to add another solution to my first answer, I'll provide another one for a second solution. The choices I gave were " A) use the selected object of the "Execution Event" (examine that, it contains a lot of infos). B) you can use AbstractSourceProvider, so you can pass your object to the application context."

A) can be used in your Handler if your object is the selection of a Structured Object like a Tree:

MyObject p = (MyObject) ((IStructuredSelection) HandlerUtil.getCurrentSelection(event)).getFirstElement();

B) The usage of a Source provider is a bit more tricky. The main idea is, that you add your object to the application context. The important snippets for Eclipse 3.x from a project that I set up after I read this blog (note: it is in german and the example it provides doesn't work): In your plugin.xml add:

  <extension point="org.eclipse.ui.services">
  <sourceProvider
        provider="com.voo.example.sourceprovider.PersonSourceProvider">
     <variable
           name="com.voo.example.sourceprovider.currentPerson"
           priorityLevel="activePartId">
     </variable>
  </sourceProvider>

Set up your own SourceProvider. Calling the "getCurrentState" you can get the variable (your Person object in this case) of that SourceProvider:

public class PersonSourceProvider extends AbstractSourceProvider{

/** This is the variable that is used as reference to the SourceProvider
 */
public static final String PERSON_ID = "com.voo.example.sourceprovider.currentPerson";
private Person currentPerson;

public PersonSourceProvider() {

}

@Override
public void dispose() {
    currentPerson = null;
}

**/**
 * Used to get the Status of the source from the framework
 */
@Override
public Map<String, Person> getCurrentState() {
    Map<String, Person> personMap = new HashMap<String, Person>();
    personMap.put(PERSON_ID, currentPerson);
    return personMap;
}**

@Override
public String[] getProvidedSourceNames() {
    return new String[]{PERSON_ID};
}

public void personChanged(Person p){
    if (this.currentPerson != null && this.currentPerson.equals(p)){
        return;
    }

    this.currentPerson = p;
    fireSourceChanged(ISources.ACTIVE_PART_ID, PERSON_ID, this.currentPerson);
}

}

In your View you register to the SourceProvider and set the Object to the object you want to transfer to your Handler.

public void createPartControl(Composite parent) {

    viewer = new TreeViewer(parent);
    viewer.setLabelProvider(new ViewLabelProvider());
    viewer.setContentProvider(new ViewContentProvider());
    viewer.setInput(rootPerson);
    getSite().setSelectionProvider(viewer);
    viewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            Person p = null;
            if (event.getSelection() instanceof TreeSelection) {
                TreeSelection selection = (TreeSelection) event.getSelection();
                if (selection.getFirstElement() instanceof Person) {
                    p = (Person) selection.getFirstElement();
                }
            }
            if (p==null) {
                return;
            }
            IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
            ISourceProviderService service = (ISourceProviderService) window.getService(ISourceProviderService.class);
            PersonSourceProvider sourceProvider = (PersonSourceProvider) service.getSourceProvider(PersonSourceProvider.PERSON_ID);
            sourceProvider.personChanged(p);
        }
    });
}

And in your Handler you can just call the PersonSourceProvider#getCurrentState to get your Objects back.

Advantage of this method is, that you can use the Objectd anywhere you want. E.g. you can even set up a PropertyTester to enable/disable UI elements according to the currently selected Object.

[Solved] Vb.net pass an object in command line arguments , You would need to pass a string - args() is a string array. You could serialise the object to a file by some means, and then pass that filename as  Command Object Parameters. The previous topic discussed Creating and Executing a Simple Command. A more interesting use for the Command object is shown in the next example, in which the SQL command has been parameterized. This modification makes it possible to reuse the command, passing in a different value for the parameter each time.

The Parameterized Command does only accept Strings. Here is an example for smaller objects:

Disclaimer: this is for Eclipse 3.x. I am not using Eclipse 4.x a lot, so you might have to adapt there in case you need it.

Create a Pluginproject (com.voo.example.commandparameter.advanced) with a View (com.voo.example.commandparameter.advanced.view) , a Command (com.voo.example.commandparameter.advanced.sysoCommand) with menu entry and Handler(com.voo.example.commandparameter.advanced.sysoCommand), and a universal Object (MyTestObject).

The Command needs a Parameter and a Parametertype in the plugin.xml, that gets passed to it:

<extension
     point="org.eclipse.ui.commands">
  <command
        id="com.voo.example.commandparameter.advanced.sysoCommand"
        name="SysoCommand">
     <commandParameter
           id="myObject"
           name="object"
           optional="true"
           typeId="com.voo.example.commandparameter.advanced.testType">
     </commandParameter>
  </command>
  <commandParameterType
        id="com.voo.example.commandparameter.advanced.testType"
        type="com.voo.example.commandparameter.advanced.MyTestObject">
  </commandParameterType>

In the Object you set atrtibutes like name and street and define a convertToString method like that:

public String convertToString() {
    return getName() +",,,"+ getStreet();
}

(you can override the toString method, too. I just used that method to set weired delimiters to the returned String) And in a Class MyParamterConverter you can transfer it back:

public class MyParameterConverter extends AbstractParameterValueConverter {

public MyParameterConverter() {

}

@Override
public String convertToString(Object parameterValue)
        throws ParameterValueConversionException {
    return parameterValue.toString();
}

/**
 * This will always create a new object. Just keep that in mind 
 * if you're trying to work with the objects.
 */
@Override
public Object convertToObject(String parameterValue)
        throws ParameterValueConversionException {

    //Split the String to get the attributes back
    String delimiter =",,,";
    String[] split = parameterValue.split(delimiter);
    String name = split[0];
    String street = split [1];

    return new MyTestObject(name, street);
}
}

Now you can call the command with a buttonclick in your view, for example:

    btnGo.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {

            MyTestObject testObject = new MyTestObject(textName.getText(),textStreet.getText());

            ICommandService cS = (ICommandService)getSite().getService(ICommandService.class);
            IHandlerService hS = (IHandlerService)getSite().getService(IHandlerService.class);

            Command sysoComm = cS.getCommand("com.voo.example.commandparameter.advanced.sysoCommand");


            HashMap<String, String> params = new HashMap<String, String>();
            params.put("myObject", testObject.convertToString());

            ParameterizedCommand pC = ParameterizedCommand.generateCommand(sysoComm, params);

            try {
                hS.executeCommand(pC, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

And the Handler can transform the passed parameters back :

public class MyObjectHandler extends AbstractHandler {

@Override
public Object execute(ExecutionEvent event) throws ExecutionException { 
    String param1 = event.getParameter("myObject");
    MyParameterConverter converter = new MyParameterConverter();
    Object convertToObject = null;

    try {
        convertToObject = converter.convertToObject(param1);
    } catch (ParameterValueConversionException e) {
        e.printStackTrace();
    }

    if (convertToObject instanceof MyTestObject) {
        MyTestObject to = (MyTestObject) convertToObject;
        System.out.println(to.toString());
    }

    return null;
}
}

This should work for most smaller sized objects that do not change while you pass them. If you need to pass bigger objects, you will have two choices: A) use the selected object of the "Execution Event" (examine that, it contains a lot of infos). B) you can use AbstractSourceProvider, so you can pass your object to the application context.

Command-Line Arguments (The Java™ Tutorials > Essential , A Java application can accept any number of arguments from the command line methods that convert a String representing a number to an object of their type. Read more posts by this author. I've been writing a few functions that either start as a job or can execute a scriptblock. I blogged about this recently with the post Building Asynchronous PowerShell Functions. As a requirement for one of these functions, I needed to pass all of the parameters in a function directly to a remote computer.

I am not really familiar with this as passing parameters to commands is quite rare. It looks like you have to use commandParameterType in the org.eclipse.ui.commands command definition to define code based on AbstractParameterValueConverter to convert between objects and the string for the parameter value.

command line arguments, The data type of the parameter variable args of the main method is an array of String !!! args[0] is the Passing command arguments to a Java program. Fact:  SqlCommand.Parameters.AddWithValue(parameterName, value) it might be more convenient to create a method accepting a parameter (name) to replace and a list of values. It is not on the Parameters level (like AddWithValue) but on command itself so it’s better to call it AddParametersWithValues and not just AddWithValues: query:

For a long time I have been focused on delivering an object via a command parameter. But in the end, the easiest workaround is to simply ignore the parameter stuff and put the desired object in a new child IExclipseContext and execute the command with that context. That way your handler gets your object injected.

Caller:

ECommandService commandService = // get commandService...
EHandlerService handlerService = // get handlerService...
IEclipseContext context = // get active or application context...

IEclipseContext childCtx = context.createChild();
childCtx.set(MyObject.class, instancOfMyObject);

ParameterizedCommand command = commandService.createCommand("my.command.id", null);
handlerService.executeHandler(command, childCtx);

In your handler:

@Execute
public void execute(@Optional MyObject myObject) {
  if(myObject != null) {
    // work with your object
  }
}

Voila, no converters or callbacks (i.e. SelectionService) needed...

PowerShell Parameters - PowerShell, & (call) - Run a command, script or function. Pipelines - Pass objects down the pipeline. Wildcards - Match multiple items. Copyright © 1999-2020 SS64. The method works, but I would argue that it’s not ideal. For one thing, you can accidentally pass in parameters in the wrong order. For another, it doesn’t provide the user with any useful feedback. I will outline the preferred method below. Using Named Parameters. Copy the following script and save it as Named_Parameters_Example_1.ps1.

16.4. argparse, The parents= argument takes a list of ArgumentParser objects, collects all the positional You must fully initialize the parsers before passing them via parents=​. Set or return the name of a parameter with the Name property. Set or return the value of a parameter with the Value property. Value is the default property of the Parameter object. Set or return parameter characteristics with the Attributes, Direction, Precision, NumericScale, Size, and Type properties.

PowerShell Parameters: Everything You Ever Wanted to Know, Instead, you need a way to pass in different values at runtime to change that allows you to seamlessly pass objects from one command to the  Summary. You should use parameters to filter queries in a secure manner. The process of using parameter contains three steps: define the parameter in the SqlCommand command string, declare the SqlParameter object with applicable properties, and assign the SqlParameter object to the SqlCommand object.

How to read Scala command line arguments, object Foo extends App { you can access your Scala command-line arguments using the args array, which is made available to you implicitly  If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like call-by-value. The object reference is passed to the function parameters. They can't be changed within the function, because they can't be changed at all, i.e. they are immutable. It's different, if we pass mutable arguments.

Comments
  • about A how did you pass the parameter ? for exmaple yObject p = (MyObject) ((IStructuredSelection) HandlerUtil.getCurrentSelection(event)).getFirstElement(); how did you pass the MYObject ?
  • I don't have to pass that explictly. You can for example do a right click on a TreeItem and use the drop down menu to call a Command. Then the active selection is passed with the event and there is no need to call a ParameterizedCommand at all. You can just use regular commands like that.
  • oh and there is an old eclipse forum post about that topic, too: eclipse.org/forums/index.php/t/155586
  • Thanks for the answer I need to pass bigger object. I didnt understand your choices. Could you please give me examples?
  • I tried it, I created class myConvert that extend from AbstractParameterValueConverter and created also commandParameterType .I did the convert from String to Object in class myConvert but when I got to the target the parameter always come as String