Basim Sherif
Basim Sherif

Reputation: 5440

How to pass class name as parameter to a function in android?

In my android application, I have two classes, say X and Y.I have another class Z and inside that class I have a static function 'print'.This function should be called from both classes, X and Y and I want to pass class name of X and Y as parameters to the function 'print' when I call print function from both classes.What I have tried is,

public class X
 {
  public static String os="Android";
  String classname="X";
  Z.print(classname);
 }

public class Y
  {
   public static String os="IOS";
   String classname="Y";
   Z.print(classname);
  }

public class Z
  {

     public static void print(String classname)

      {

       System.out.println(classname.os);

      }
  }

But eclipse throws an error "os cannot be resolved or is not a field".I know the method I have used for passing class name is wrong.Can anyone guide me to solve this problem?...Thanks in advance....

Upvotes: 0

Views: 2561

Answers (4)

sujith
sujith

Reputation: 2421

Move the Z.print() to a method body.

Upvotes: 0

Rohan Britto
Rohan Britto

Reputation: 25

Why don't you directly pass os as the parameter?

class X
 {
  public static String os="Android";
  String classname="X";
  void print()
  {
    Z.print(os);
}
}

class Y
  {
   public static String os="IOS";
   String classname="Y";
   void print()
{
    Z.print(os);
}
}

class Z
  {

 public static void print(String x)

  {

   System.out.println(x);

  }

}

Upvotes: 0

You can call getName method of class.

YourClass.class.getName();

In your case when you call print method of Z class, call like this:

Z.print(Y.class.getName());

Upvotes: 2

Wyzard
Wyzard

Reputation: 34563

In your print method, the classname argument is an ordinary Java string. It doesn't have a field called os.

If you want to pass both the class name and OS name to the print method, you'll need to make print take two string arguments:

public static void print(String classname, String os)
{
  System.out.println(classname + ", " + os);
}

and pass both values when calling the it:

Z.print(classname, os);

Your other error is that your X and Y classes have code outside a method, which isn't allowed.

Upvotes: 0

Related Questions