Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: squidgetx on January 15, 2013, 09:19:24 pm

Title: passing a type?
Post by: squidgetx on January 15, 2013, 09:19:24 pm
I actually found a workaround for this problem, but I figured it's still worth asking about. Basically, I'm wondering if it's possible to pass an object type as an argument to a function. How do you do it? And is it considered good/bad practice?
Title: Re: passing a type?
Post by: cooliojazz on January 15, 2013, 10:51:36 pm
I can't tell you about practice, cause ive never taken a programming class in my life, and just randomly pick up things from places, but it is probably possible, at least depending on what you mean by "type".  Assuming you mean class, you could always just do:
Code: [Select]
static public void main(String[] s) {
  printType(String.class);
  printType("Hello".getClass());
  printType(Integer.class);
}

static public void printType(Class c) {
  System.out.println(c.getName());
  if (c.equals(String.class)) {
    System.out.println("Strings are cool!");
  }
}


//Prints:
java.lang.String
Strings are cool!
java.lang.String
Strings are cool!
java.lang.Integer

If you mean something else... then i'm not entirely sure what you mean :P
Title: Re: passing a type?
Post by: ElementCoder on January 16, 2013, 10:34:56 am
I guess you could pass a class (pretty much the same as coolio does):
Code: [Select]
private void foo(Class<?> t){
    if(t == String.class){ ... }
    else if(t == int.class){ ... }
}

private void bar()
{
   foo(String.class);
}
As far as practise goes, I don't see why this would be bad tbh :) Using Class<?> instead of just Class will save you an error about raw types though.