java - 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.
解决方案
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;
}
}
推荐阅读
- sharepoint - 上传的图像文件在 sharepoint 中没有任何预览
- emacs - elisp 中的赋值
- javascript - 从数据 url 设置 fabric.js 画布背景
- blazor - Blazor @onmousedown 无法识别长按
- python - 如何在包含 html 和纯文本消息正文的 python 中发送邮件?
- reactjs - 无法在 web-worker 中导入 fabric.js?
- javascript - 有没有更好看的方法来比较 Javascript 中可能为 0 也可能不是 0 的 3 个值?
- typescript - 打字稿泛型类型
- c# - 我应该使用哪个 NuGet 包版本的 Microsoft.CrmSdk.CoreAssemblies?
- amazon-product-api - Amazon Advertising Api - 报告数据处理(ACOS、ROAS、有机销售、广告销售)