Author Topic: passing a type?  (Read 3022 times)

0 Members and 1 Guest are viewing this topic.

Offline squidgetx

  • Food.
  • CoT Emeritus
  • LV10 31337 u53r (Next: 2000)
  • *
  • Posts: 1881
  • Rating: +503/-17
  • rawr.
    • View Profile
passing a type?
« 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?

Offline cooliojazz

  • Support Staff
  • LV7 Elite (Next: 700)
  • *******
  • Posts: 619
  • Rating: +66/-9
  • I omnoms on your soul
    • View Profile
    • Unreal Phantasies
Re: passing a type?
« Reply #1 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
Spoiler For Random signess:
You can not beat my skills.
Trust me.
So don't even try.
And remember never to trust someone who says, "Trust me."

TI File Editor Progress: Remade in java like a boss. 50% we'll call it? IDK =P
Java Libraries: JIRC - 90% JTIF - 5%
TI Projects: Unreal Notator - -5000%
Nomcraft, a Bukkit mod
Some of the music I write can be found here | The Rest Should Be Here (Bandcamp)

Offline ElementCoder

  • LV7 Elite (Next: 700)
  • *******
  • Posts: 611
  • Rating: +42/-2
    • View Profile
Re: passing a type?
« Reply #2 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.
« Last Edit: January 16, 2013, 11:05:30 am by ElementCoder »

Some people need a high five in the face... with a chair.
~EC