首页 > 解决方案 > Is it possible to create a method which can be invoked directly from a primitive type variable in java?

问题描述

Methods which are invoked from an object reference like StringBuilder class's .append() method or directly from a class like Math.pow() can be easily created.

But is it possible to create a method such as .toUpperCase() or .toLowerCase() which can be invoked form any string type variable? A method that can be invoked from a certain primitive type variable.

标签: javamethods

解决方案


toUpperCase()并且toLowerCase()是 String 中已经包含的方法,可以直接访问字符串。

不知何故,如果你创建了一个只包含一个字符串变量的类和一个设置它的构造函数,你不能简单地调用MyStringClass string = "message";

在这里您可以尝试:

MyClass myObject = new MyClass(/*Parameter if exists.*/);
//Or.
myObject.setString();
String string = myObject.getString()/*And another method like toUpperCase() or toLowerCase() if you want*/;

现在您已经创建了一个基于类对象的字符串。

在第一个示例中,您创建了一个字符串。现在,如果你想用你自己创建的方法来影响字符串,你可以使用这样的东西:

public class MyClass {
  ...

  public static String myStringMethod(/*Pass a string that you want to modify if so.*/){
    return "message";
    //Or based on a parameter.
    return string+=string;//For example;
  }

  //Or using an non-returning method "void".

  public static void myMethod(String string, String string2, String string_ /*You can even pass multiple parameters, separated with commas.*/){
    string = "Hello ";
    string2 = "World!;
    string_ = string+string2;
  }
}

推荐阅读