1

I would like to create a method, which will, besides other things, create an object named like the method argument. (I apologize if it is solved somewhere else, didn't find it) Something like as follows:

public return_type method (String ARGUMENT1)
{
  ...
  ClassOfSomeKind objectOfSomeKind someprefix_ARGUMENT1 = new ClassOfSomeKind();
}
2
  • 1
    As an aside, it's useful to make even your sample code follow naming conventions, e.g. string objectName as the parameter and SomeClass instead of objectOfSomeKind. Commented Mar 20, 2015 at 8:24
  • I think you need to explain why you want this. Commented Mar 20, 2015 at 8:30

2 Answers 2

3

That's naming a variable - not an object. Objects don't have names, as such. (You can have a field called name of course, but it's not a general thing.)

Variable names are usually only relevant at compile time - so it doesn't really make sense to do this dynamically.

It sounds like you probably want a Map<String, YourClassType> so that you can associate each object with a name and then fetch it later. So something like:

class Foo {
    private final Map<String, Bar> bars = new HashMap<>();

    public Bar createBar(String name) {
        Bar bar = new Bar();
        bars.put(name, bar);
        return bar;
    }

    public void processBar(String name) {
        Bar bar = bars.get(name);
        if (bar == null) {
            // No Bar for that name...
            // Maybe throw an exception?
        }
        // Do something with bar
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for answer, but as i am a beginner, could you please explain a little? What i need is to create a "shortcut" function, which i use in different places in code, but everytime i use it, it creates same object type, but with unique content and i need to be able to get to those different objects later. Could you please extend my code with Map so i would iunderstand it better?
@user3338991: It's hard to do so when we know so little about what you're trying to achieve. I've added an example, but it's not entirely clear whether that's what you need...
2

You could use a Map where the key is your variable name and the value is ObjectOfSomeKind object:

public class YourClass {
  ...
  private Map<String, ObjectOfSomeKind> yourHashMap= new HashMap<String, ObjectOfSomeKind>();

  public method (string ARGUMENT1)
  {
    yourHashMap.put("someprefix_"+ARGUMENT1, new ObjectOfSomeKind ("someprefix_"+ARGUMENT1));

  }
  ...

  public retrieveMethod (string ARGUMENT1)
  {
    ObjectOfSomeKind objectOfSomeKindRetrieved = yourHashMap.get("someprefix_"+ARGUMENT1);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.