JAVA中常用类的常用方法
java中类的用法

java中类的用法Java是一种面向对象的编程语言,类是面向对象编程的基本概念之一。
在Java中,类是一种模板,它用来描述一类对象的方法和属性。
可以通过创建类的对象来使用它的方法和属性。
本文将介绍Java中类的用法。
一、定义类Java中定义类的语法如下:```java public class ClassName { // 类的成员变量 // 类的构造函数 // 类的方法 } ```其中,类名要遵循标识符的命名规范。
类的成员变量是类的属性,它们用于存储对象的状态。
类的构造函数用于创建对象并初始化它的成员变量。
类的方法用于定义对象的行为。
二、成员变量Java中的成员变量也称为类的属性,用于存储对象的状态。
成员变量可以是基本类型、引用类型或数组类型。
在类的定义中,成员变量要放在构造函数和方法的前面。
成员变量可以通过类的对象来访问和修改。
```java public class Person { private String name; private int age;public Person(String name, int age){ = name; this.age = age; }public String getName() { return name; }public void setName(String name){ = name; }public int getAge() { return age; }public void setAge(int age){ this.age = age; } } ```在上面的例子中,Person类有两个成员变量name和age,它们都使用private关键字修饰,表示只能在类内部访问。
同时,这个Person类提供了一个有参构造函数和getter、setter方法,用来访问和修改成员变量。
三、构造函数Java中的构造函数用于创建对象并初始化它的成员变量。
Java-Method类常用方法详解

Java-Method类常⽤⽅法详解⼀、Method类的定义Method类位于 ng.reflect 包中,主要⽤于在程序运⾏状态中,动态地获取⽅法信息⼆、Method类的常⽤⽅法1、getAnnotatedReturnType()返回⼀个AnnotatedType对象,该对象表⽰使⽤⼀个类型来指定由该可执⾏⽂件表⽰的⽅法/构造函数的返回类型public class MethodTest {public String test() {return null;}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");AnnotatedType methodAnnotatedReturnType = method.getAnnotatedReturnType();// class ng.StringSystem.out.println(methodAnnotatedReturnType.getType());}}123456789101112132、getAnnotatedExceptionTypes()返回⼀个AnnotatedType对象数组,这些对象表⽰使⽤类型来指定由该可执⾏⽂件表⽰的⽅法/构造函数声明的异常public class MethodTest {public void test() throws NullPointerException, ClassNotFoundException {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");AnnotatedType[] annotatedExceptionTypes = method.getAnnotatedExceptionTypes();for (AnnotatedType annotatedExceptionType : annotatedExceptionTypes) {// class ng.NullPointerException// class ng.ClassNotFoundExceptionSystem.out.println(annotatedExceptionType.getType());}}}12345678910111213public class MethodTest {public void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");AnnotatedType annotatedReceiverType = method.getAnnotatedReceiverType();// class lang.reflect.MethodTestSystem.out.println(annotatedReceiverType.getType());}}12345678910114、getAnnotation(Class<T> annotationClass)如果该⽅法对象存在指定类型的注解,则返回该注解,否则返回null只有类级别的注解会被继承得到,对于其他对象⽽⾔,getAnnotation() ⽅法与 getDeclaredAnnotation() ⽅法作⽤相同@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface MethodAnnotation {String key();String value();}public class MethodTest {@MethodAnnotation(key = "key", value = "value")public void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");MethodAnnotation annotation = method.getAnnotation(MethodAnnotation.class);// @lang.reflect.MethodAnnotation(value=value, key=key)System.out.println(annotation);}}123456789101112131415161718如果该⽅法对象存在指定类型的注解,则返回该注解,否则返回null只有类级别的注解会被继承得到,对于其他对象⽽⾔,getAnnotation() ⽅法与 getDeclaredAnnotation() ⽅法作⽤相同6、getAnnotationsByType(Class<T> annotationClass)如果该⽅法对象存在指定类型的注解,则返回该注解数组,否则返回null只有类级别的注解会被继承得到,对于其他对象⽽⾔,getAnnotationsByType() ⽅法与 getDeclaredAnnotationsByType() ⽅法作⽤相同getAnnotationsByType() ⽅法与 getAnnotation() ⽅法的区别在于 getAnnotationsByType() ⽅法会检查修饰该⽅法对象的注解是否为可重复类型注解,如果是则会返回该参数类型的⼀个或多个注解@Repeatable ⽤于声明注解为可重复类型注解,当声明为可重复类型注解后,如果⽅法注解仍为⼀个,则 getAnnotation() ⽅法会正常返回,如果⽅法注解为多个,则 getAnnotation()⽅法会返回null@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Repeatable(RepeatableAnnotation.class)public @interface MethodAnnotation {String key();String value();}@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@interface RepeatableAnnotation {MethodAnnotation[] value();}public class MethodTest {@MethodAnnotation(key = "key1", value = "value1")@MethodAnnotation(key = "key2", value = "value2")public void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");MethodAnnotation[] annotationsByType = method.getAnnotationsByType(MethodAnnotation.class);// [@lang.reflect.MethodAnnotation(value=value1, key=key1), @lang.reflect.MethodAnnotation(value=value2, key=key2)]System.out.println(Arrays.toString(annotationsByType));}}1234567891011121314151617181920212223242526如果该⽅法对象存在指定类型的注解,则返回该注解数组,否则返回null只有类级别的注解会被继承得到,对于其他对象⽽⾔,getAnnotationsByType() ⽅法与 getDeclaredAnnotationsByType() ⽅法作⽤相同 8、getAnnotations()返回该⽅法对象上的所有注解,如果没有注解,则返回空数组只有类级别的注解会被继承得到,对于其他对象⽽⾔,getAnnotations() ⽅法与 getDeclaredAnnotations() ⽅法作⽤相同@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface MethodAnnotation {String key();String value();}@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface TestAnnotation {String key();String value();}public class MethodTest {@MethodAnnotation(key = "key1", value = "value1")@TestAnnotation(key = "key2", value = "value2")public void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");Annotation[] annotations = method.getAnnotations();for (Annotation annotation : annotations) {// @lang.reflect.MethodAnnotation(value=value1, key=key1)// @lang.reflect.Parameter.TestAnnotation(key=key2, value=value2)System.out.println(annotation);}}}12345678910111213141516171819202122232425269、getDeclaredAnnotations()返回该⽅法对象上的所有注解,如果没有注解,则返回空数组只有类级别的注解会被继承得到,对于其他对象⽽⾔,getAnnotations() ⽅法与 getDeclaredAnnotations() ⽅法作⽤相同 10、getModifiers()返回修饰该⽅法对象修饰符的整数形式,使⽤ Modifier 类对其进⾏解码public class MethodTest {public void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");// publicSystem.out.println(Modifier.toString(method.getModifiers()));}}1234567891011、getName()返回⽅法对象名称public class MethodTest {public void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");// testSystem.out.println(method.getName());}}1234567891012、isAnnotationPresent(Class<? extends Annotation> annotationClass)如果该⽅法对象上有指定类型的注解,则返回true,否则为falsepublic class MethodTest {@MethodAnnotation(key = "key", value = "value")public void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");// trueSystem.out.println(method.isAnnotationPresent(MethodAnnotation.class));789101113、isVarArgs()如果该⽅法对象的参数中存在可变参,则返回true,否则为falsepublic class MethodTest {public void test(String ... args) {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test", String[].class);// trueSystem.out.println(method.isVarArgs());}}1234567891014、getDeclaringClass ()返回该⽅法对象表⽰的⽅法所在类的Class对象public class MethodTest {public void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");Class<?> declaringClass = method.getDeclaringClass();// class lang.reflect.MethodTestSystem.out.println(declaringClass);}}123456789101115、getAnnotatedParameterTypes()返回⼀个AnnotatedType对象数组,这些对象表⽰使⽤类型来指定由该可执⾏⽂件表⽰的⽅法/构造函数的形式参数类型public class MethodTest {public void test(String name, Integer age) {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test", String.class, Integer.class);System.out.println(annotatedParameterType.getType());}}}123456789101112131416、getParameterAnnotations()返回⼀组注解数组,这些注解以声明顺序修饰该⽅法对象的参数public class MethodTest {public void test(@ParameterAnnotation(key = "key1", value = "value1") String name,@ParameterAnnotation(key = "key2", value = "value2") Integer age) {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test", String.class, Integer.class);Annotation[][] parameterAnnotations = method.getParameterAnnotations();// [[@lang.reflect.ParameterAnnotation(key=key1, value=value1)], [@lang.reflect.ParameterAnnotation(key=key2, value=value2)]] System.out.println(Arrays.deepToString(parameterAnnotations));}}12345678910111217、getParameterCount()返回该⽅法对象的参数个数 (⽆论是显式声明的还是隐式声明的或不声明的)public class MethodTest {public void test(String name, Integer age) {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test", String.class, Integer.class);// 2System.out.println(method.getParameterCount());}}1234567返回⼀个参数对象数组,该数组表⽰该⽅法对象的所有参数public class MethodTest {public void test(String name, Integer age) {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test", String.class, Integer.class); Parameter[] parameters = method.getParameters();for (Parameter parameter : parameters) {// ng.String name// ng.Integer ageSystem.out.println(parameter);}}}123456789101112131419、getDefaultValue()返会该注解⽅法对象表⽰的成员默认值如果成员属于基本数据类型,则返回对应的包装类实例如果没有默认值或者该⽅法实例不表⽰注解⽅法,则返回null@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface MethodAnnotation {String key() default "default key";String value() default "default value";}public class MethodTest {public static void main(String[] args) throws Exception {Method key = MethodAnnotation.class.getMethod("key");Method value = MethodAnnotation.class.getMethod("value");Object defaultValue1 = key.getDefaultValue();Object defaultValue2 = value.getDefaultValue();// default keySystem.out.println(defaultValue1);// default valueSystem.out.println(defaultValue2);}}123456789181920212220、getParameterTypes()返回⼀个Class对象数组,该数组以声明顺序表⽰该⽅法对象的参数对象,会擦除泛型public class MethodTest<T> {public void test(T t) {}public void test(LinkedList<Integer> list) {}public static void main(String[] args) throws Exception {Method objectMethod = MethodTest.class.getMethod("test", Object.class);Method listMethod = MethodTest.class.getMethod("test", LinkedList.class);Class<?>[] objectParameterTypes = objectMethod.getParameterTypes();// [class ng.Object]System.out.println(Arrays.toString(objectParameterTypes));Class<?>[] listParameterTypes = listMethod.getParameterTypes();// [class java.util.LinkedList]System.out.println(Arrays.toString(listParameterTypes));}}12345678910111213141516171821、getReturnType()返回⼀个Class对象,该Class对象表⽰该⽅法对象的返回对象,会擦除泛型public class MethodTest<T> {public T test(T t) {return t;}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getMethod("test", Object.class);Class<?> returnType = method.getReturnType();// class ng.ObjectSystem.out.println(returnType);}}1211121322、getGenericReturnType()返回⼀个Type对象,该Type对象表⽰该⽅法对象的返回类型,会保留泛型public class MethodTest<T> {public T test(T t) {return t;}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getMethod("test", Object.class);Type genericReturnType = method.getGenericReturnType();// TSystem.out.println(genericReturnType);}}1234567891011121323、getExceptionTypes()返回⼀个Class对象数组,该数组表⽰由该⽅法对象抛出的异常对象,会擦除泛型public class MethodTest<T> {public <T extends Exception> void test() throws T, NullPointerException {} public static void main(String[] args) throws Exception {Method method = MethodTest.class.getMethod("test");Class<?>[] exceptionTypes = method.getExceptionTypes();// [class ng.Exception, class ng.NullPointerException]System.out.println(Arrays.toString(exceptionTypes));}}123456789101124、getGenericExceptionTypes()返回⼀个Type对象数组,该数组表⽰由该⽅法对象抛出的异常类型,会保留泛型public class MethodTest<T> {Type[] genericExceptionTypes = method.getGenericExceptionTypes();// [T, class ng.NullPointerException]System.out.println(Arrays.toString(genericExceptionTypes));}}123456789101125、getTypeParameters()返回⼀个TypeVariable对象数组,该数组表⽰该⽅法对象声明列表上的类型变量数组public class MethodTest<T, V> {public <T, V> void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getMethod("test");TypeVariable<Method>[] typeParameters = method.getTypeParameters();// [T, V]System.out.println(Arrays.toString(typeParameters));}}123456789101126、toString()返回该⽅法对象的字符串表⽰形式,会擦除泛型public class MethodTest<T, V> {public <T, V> void test() {}public static void main(String[] args) throws Exception {Method method = MethodTest.class.getMethod("test");// public void lang.reflect.MethodTest.test()System.out.println(method.toString());}}1234567891027、toGenericString()public static void main(String[] args) throws Exception {Method method = MethodTest.class.getMethod("test");// public <T,V> void lang.reflect.MethodTest.test()System.out.println(method.toGenericString());}}1234567891028、isAccessible()获取该⽅法对象的可访问标志public class MethodTest {private void test() {}}public class Test {public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");// falseSystem.out.println(method.isAccessible());}}1234567891011121329、setAccessible(boolean flag)设置该⽅法对象的可访问标志在其他类⾥调⽤该⽅法对象时,如果该⽅法为私有⽅法,需要设置访问标志为true,否则会报异常public class MethodTest {private void test() {}}public class Test {public static void main(String[] args) throws Exception {Method method = MethodTest.class.getDeclaredMethod("test");method.setAccessible(true);// testSystem.out.println(method.getName());}}12312131430、isDefault()判断该⽅法对象是否为默认⽅法,如果是则返回true,否则为falsepublic interface Interface {default void test() {System.out.println("这是⼀个默认⽅法");}}public class MethodTest implements Interface {public static void main(String[] args) throws Exception {Method method = MethodTest.class.getMethod("test");// trueSystem.out.println(method.isDefault());}}12345678910111213141531、isSynthetic()判断该⽅法对象是否为合成⽅法,如果是则返回true,否则为false在内部类InnerClass中,name是⼀个私有属性,⽽我们在外部类MethodTest中,直接引⽤了这个属性,因此编译器通过⽣成⼀个合成⽅法,⽤于绕开private私有属性的限制public class MethodTest {private class InnerClass {private String name = "⼩明";}public static void main(final String[] arguments) {InnerClass innerClass = new MethodTest().new InnerClass();System.out.println("name: " + );Method[] declaredMethods = innerClass.getClass().getDeclaredMethods();for (Method declaredMethod : declaredMethods) {// 【static ng.String lang.reflect.MethodTest$InnerClass.access$100(lang.reflect.MethodTest$InnerClass)】 isSynthetic(): true System.out.println("【" + declaredMethod + "】" + " isSynthetic(): " + declaredMethod.isSynthetic());}}}12341314151617有关synthetic的相关内容,⼩伙伴可以看下这⾥Java 中冷门的 synthetic 关键字原理解读32、isBridge()判断该⽅法对象是否桥接⽅法,如果是则返回true,否则为false桥接⽅法: 是 JDK1.5 引⼊泛型后,为了使Java的泛型⽅法⽣成的字节码和 1.5 版本前的字节码相兼容,由编译器⾃动⽣成的⽅法public interface Interface<T> {T test(T t);}public class MethodTest implements Interface<String> {@Overridepublic String test(String str) {return str;}public static void main(final String[] arguments) {Method[] declaredMethods = MethodTest.class.getDeclaredMethods();for (Method declaredMethod : declaredMethods) {//【public static void lang.reflect.MethodTest.main(ng.String[])】 isBridge(): false//【public ng.String lang.reflect.MethodTest.test(ng.String)】 isBridge(): false//【public ng.Object lang.reflect.MethodTest.test(ng.Object)】 isBridge(): trueSystem.out.println("【" + declaredMethod + "】" + " isBridge(): " + declaredMethod.isBridge());}}}12345678910111213141516171819202122。
攀枝花学院Java实验五 常用类

实验报告附页String s7 = new String("123.678");int n1=Integer.parseInt(s6);//将s6转化成int型数据。
double n2=Double.parseDouble(s7); //将s7转化成double型数据。
double m=n1+n2;System.out.println(m);String s8=String.valueOf(m); //String调用valuOf(int n)方法将m转化为字符串对象position=s8.indexOf(".");String temp=s8.substring(position+1);System.out.println("数字"+m+"有"+temp.length()+"位小数") ;@SuppressWarnings("unused")String s9=new String("ABCDEF");char a[]=s8.toCharArray(); //将s8存放到数组a中。
for(int i=a.length-1;i>=0;i--){System.out.print(" "+a[i]);}}}运行结果:将上面程序按如下要求修改,并运行:(1)程序中的s6改写成String s6=new String(“1a12b”);运行时提示怎样的错误?Exception in thread "main" ng.NumberFormatException: For input string: "1a12b"at ng.NumberFormatException.forInputString(Unknown Source)at ng.Integer.parseInt(Unknown Source)at ng.Integer.parseInt(Unknown Source)at xiti2.xiugai.main(xiugai.java:39)(2)请用数组a的前3个单元创建一个字符串并输出该串。
java基础常用的方法

java基础常用的方法Java基础常用的方法Java作为一门流行的编程语言,拥有着丰富的基础方法。
本文将介绍一些Java基础常用的方法,帮助读者更好地理解和使用这门语言。
一、字符串处理方法在Java中,字符串是一种常用的数据类型,因此字符串处理方法也是开发中常用到的。
下面是一些常见的字符串处理方法:1. length():返回字符串的长度。
javaString str = "Hello World";int len = str.length(); len的值为112. charAt():返回指定索引位置的字符。
javaString str = "Hello World";char ch = str.charAt(4); ch的值为'o'3. substring():返回指定索引范围内的子串。
javaString str = "Hello World";String subStr = str.substring(6); subStr的值为"World"4. concat():将指定字符串连接到原字符串末尾。
javaString str1 = "Hello";String str2 = "World";String result = str1.concat(str2); result的值为"HelloWorld"5. replace():替换字符串中的指定字符或子串。
javaString str = "Hello World";String newStr = str.replace('o', 'a'); newStr的值为"Hella Warld"6. toUpperCase()和toLowerCase():将字符串转换为大写或小写。
JavaBigDecimal类常用方法

JavaBigDecimal类常⽤⽅法最近⼯作中接触到了 Java BigDecimal类,准备整理⼀下⽤到的⼏个常⽤⽅法。
简介Java在java.math包中提供的API类BigDecimal,⽤来对超过16位有效位的数进⾏精确的运算。
双精度浮点型变量double可以处理16位有效数。
在实际应⽤中,需要对更⼤或者更⼩的数进⾏运算和处理。
float和double只能⽤来做科学计算或者是⼯程计算,在商业计算中要⽤java.math.BigDecimal。
BigDecimal所创建的是对象,我们不能使⽤传统的+、-、*、/等算术运算符直接对其对象进⾏数学运算,⽽必须调⽤其相对应的⽅法。
⽅法中的参数也必须是BigDecimal的对象。
构造器是类的特殊⽅法,专门⽤来创建对象,特别是带有参数的对象。
构造器BigDecimal(int) 创建⼀个具有参数所指定整数值的对象。
BigDecimal(double) 创建⼀个具有参数所指定双精度值的对象。
BigDecimal(long) 创建⼀个具有参数所指定长整数值的对象。
BigDecimal(String) 创建⼀个具有参数所指定以字符串表⽰的数值的对象。
这⼏个都是常⽤的构造器,他们返回的对象都是BigDecimal对象。
换⽽⾔之,将各个类型的值转换为BigDecimal对象,就是通过构造器。
反过来说,将BigDecimal对象转换为其他类型的对象,我们通过以下⼏种:toString() 将BigDecimal对象的数值转换成字符串。
doubleValue() 将BigDecimal对象中的值以双精度数返回。
floatValue() 将BigDecimal对象中的值以单精度数返回。
longValue() 将BigDecimal对象中的值以长整数返回。
intValue() 将BigDecimal对象中的值以整数返回。
常⽤⽅法BigDecimal b1 = new BigDecimal("20");BigDecimal b2 = new BigDecimal("30");b1.add(b2) :加法,求两个BigDecimal类型数据的和。
java中实现定时任务的常用方式,以及差异和注意事项。

java中实现定时任务的常用方式,以及差异和注意事项。
1.Timer类:Timer类是Java中最基本的定时任务类,它可以在指定时间后执行一次或定时重复执行任务。
2. ScheduledExecutorService接口:ScheduledExecutorService是Java 5中新增的定时任务接口,它可以实现更灵活、更可控、更安全的定时任务。
3. Quartz框架:Quartz是一个优秀的任务调度框架,它提供了很多高级功能,比如任务分组、任务优先级、任务依赖关系等。
不同的方式实现定时任务的差异在于可定制性、稳定性、可靠性等方面。
Timer类虽然简单易用,但不够灵活,容易出现线程安全问题;而ScheduledExecutorService虽然性能更好、更安全,但也有其局限性,比如无法处理复杂的任务依赖关系。
Quartz框架则是一个功能强大的工具,但也需要花费一些学习成本。
在使用定时任务时,需注意以下事项:
1. 必须定义任务执行的频率、时间和处理逻辑。
2. 需要考虑任务对系统性能的影响,比如任务执行时间过长可能会导致系统卡顿。
3. 需要考虑任务的并发性,尤其是在多线程环境下。
4. 需要合理地使用线程池和锁,以确保任务执行的可靠性和线程安全性。
总之,在实现定时任务时,需要根据具体需求选择合适的方案,并注意任务的可定制性、稳定性、可靠性等方面的问题。
JavaString类的常用方法(字符串替换)

JavaString类的常用方法(字符串替换)Java中的String类提供了多个方法用于替换字符串,常用方法包括:1. `replace(char oldChar, char newChar)`:将字符串中所有的指定字符oldChar替换为newChar。
```javaString str = "hello world";String replacedStr = str.replace('o', 'e');System.out.println(replacedStr); // 输出: helle werld```2. `replace(CharSequence target, CharSequence replacement)`:将字符串中所有的指定字符序列target替换为replacement。
```javaString str = "hello world";String replacedStr = str.replace("world", "Java");System.out.println(replacedStr); // 输出: hello Java```3. `replaceAll(String regex, String replacement)`:使用正则表达式regex匹配的所有字符串替换为replacement。
```javaString str = "hello 123 world";String replacedStr = str.replaceAll("\\d+", "Java");System.out.println(replacedStr); // 输出: hello Java world ```4. `replaceFirst(String regex, String replacement)`:使用正则表达式regex匹配的第一个字符串替换为replacement。
Java常用方法大全

Java常用方法大全字符串1、获取字符串的长度length()2 、判断字符串的前缀或后缀与已知字符串是否相同前缀startsWith(String s)后缀endsWith(String s)3、比较两个字符串equals(String s)4、把字符串转化为相应的数值int型Integer.parseInt(字符串)long型Long.parseLong(字符串)float型Folat.valueOf(字符串).floatValue()double型Double.valueOf(字符串).doubleValue()4、将数值转化为字符串valueOf(数值)5、字符串检索indexOf(Srting s) 从头开始检索indexOf(String s ,int startpoint) 从startpoint处开始检索如果没有检索到,将返回-16、得到字符串的子字符串substring(int startpoint) 从startpoint处开始获取substring(int start,int end) 从start到end中间的字符7、替换字符串中的字符,去掉字符串前后空格replace(char old,char new) 用new替换oldtrim()8、分析字符串StringTokenizer(String s) 构造一个分析器,使用默认分隔字符(空格,换行,回车,Tab,进纸符)StringTokenizer(String s,String delim) delim是自己定义的分隔符nextToken() 逐个获取字符串中的语言符号boolean hasMoreTokens() 只要字符串还有语言符号将返回true,否则返回false countTokens() 得到一共有多少个语言符号文本框和文本区1、文本框TextField() 构造文本框,一个字符长TextField(int x) 构造文本框,x个字符长TextField(String s) 构造文本框,显示ssetText(String s) 设置文本为sgetText() 获取文本setEchoChar(char c) 设置显示字符为csetEditable(boolean) 设置文本框是否可以被修改addActionListener() 添加监视器removeActionListener() 移去监视器2、文本区TextArea() 构造文本区TextArea(String s) 构造文本区,显示sTextArea(String s,int x,int y) 构造文本区,x行,y列,显示s TextArea(int x,int y) 构造文本区,x行,y列TextArea(String s,int x,ing y,int scrollbar)scrollbar的值是:TextArea.SCROLLBARS_BOTHTextArea.SCROLLBARS_VERTICAL_ONL YTextArea.SCROLLBARS_HORIZONTAL_ONL Y TextArea.SCROLLBARS_NONEsetText(String s) 设置文本为sgetText() 获取文本addTextListener() 添加监视器removeTextListener() 移去监视器insert(String s,int x) 在x处插入文本sreplaceRange(String s,int x,int y) 用s替换从x到y处的文本append(String s) 在文本的最后追加文本sInt getCaretPosition(int n) 获取文本区中光标的位置按钮1、按钮Button() 构造按钮Button(String s) 构造按钮,标签是ssetLabel(String s) 设置按钮标签是sgetLabel() 获取按钮标签addActionListener() 添加监视器removeActionListener() 移去监视器标签1、标签Label() 构造标签Label(String s) 构造标签,显示sLabel(String s,int x)x是对齐方式,取值:Label.LEFTLabel.RIGHTLabel.CENTERsetText(String s) 设置文本sgetText() 获取文本setBackground(Color c) 设置标签背景颜色setForeground(Color c) 设置字体颜色选择框1、选择框Checkbox() 构造选择框Checkbox(String s) 构造选择框,给定标题sCheckbox(String s,boolean b) b设定初始状态Checkbox(String s,boolean b,CheckboxGroup g) g设定了所属的组(有了组就成为单选框)addItemListener() 添加监视器removeItemListener() 移去监视器getState() 返回选择框的是否选中状态setState(boolean b) 设置选择框的状态getLabel() 获取选择框的标题setLabel(String s) 设置选择框的标题为s选择控件和滚动列表1、选择控件Choice() 构造选择控件add(String s) 向选择控件增加一个选项addItemListener() 添加监视器removeItemListener() 移去监视器getSelectedIndex() 返回当前选项的索引getSelectedItem() 返回当前选项的字符串代表insert(String s,int n) 在n处插入选项sremove(int n)removeAll()2、滚动列表List() 构造滚动列表List(int n) 参数n是可见行数List(int n,boolean b) 参数b是设置是否可以多项选择add(String s) 向列表的结尾增加一个选项add(String s,int n) 在n处增加一个选项AddActionListener() 滚动列表添加监视器addItemListener() 滚动列表上的选项添加监视器remove(int n) 删除n初的选项remnoveAll() 删除全部选项getSelectedIndex() 返回当前选项的索引getSelectedItem() 返回当前选项的字符串代表3、组件类的一些常用方法void setBackground(Color c) 设置组件背景颜色void setForeground(Color c) 设置组件前景颜色void setFonts(Font f) 设置组件字体void setBounds(int x,int y,int w,int h) 设置坐标,x,y表示在容器中坐标,w,h表示宽和高void setLocation(int x,int y) 移动到x,y 处void setSize(int w,int h) 设置宽和高void setVisible(boolean b) 设置组建是否可见int getBounds().wigth 获取宽int getBounds().height 获取高int getBounds().x 获取x 坐标int getBounds().y 获取y 坐标Toolkit getToolkit() 获取工具包对void setEnabled(boolean b) 设置是否可以使用(默认可以)窗口和菜单1、窗口Frame() 构造窗口Frame(String s) 窗口标题是ssetBounds(int x,int y,int w,int h) 窗口位置x,y,宽w,高ysetSize(int w,int h) 设置窗口位置(单位是像素)setBackground(Color c) 设置背景颜色setVisible(boolean b) 设置窗口是否可见pack() 窗口出现时紧凑setTitle(String s) 设置标题为sgetTitle() 获取标题setResizable(boolean b) 设置窗口大小是否可以调整2、菜单条Menubar() 构造菜单条setMenubar() 窗口添加菜单条3、菜单Menu() 构造菜单Menu(String s) 构造菜单,标题saddadd(MenuItem item) 菜单增加菜单选项itemadd(String s) 向菜单增加选项sgetItem(int n) 获取n处的选项getItemCount() 获取选项数目insert(MenuItem item,int n) 在n处插入菜单选项iteminsert(String s,int n) 在n处插入菜单选项remove(int n) 删除菜单的n处的菜单选项removeAll() 删除全部4、菜单项MenuItem() 构造菜单项MenuItem(String s) 构造标题是s的菜单项setEnabled(boolean b) 设置是否可以被选择getLabel() 得到菜单选项名addActionListener() 添加监视器5、有关菜单的技巧addSeparator() 增加菜单分割线CheckboxMenuItem() 复选框菜单项setShortcut(MenuShortcut k) 设置快捷键(k取值KeyEvent.VK_A----KeyEvent.VK_Z)建立对话框1、Dialog类Dialog(Frame f,String s) 构造对话框,初始不可见,s是标题,f是对话框所依赖的窗口Dialog(Frame f,String s,boolean b) b设置初始是否可见getTitle() 获取对话框标题setTitle(String s) 设置对话框标题setModal(boolean b) 设置对话框模式setSize(int w,int h) 设置对话框大小setVisible(boolean b) 显示或隐藏对话框2、FileDialog类Filedialog(Frame f,String s,int mode) mode的值是fileDialog.LOAD或者fileDialog.SAVE public String getDirectory() 获取当前文件对话框中显示的文件所属目录public String getFile() 获取当前文件对话框中文件的字符串表示,不存在返回nullJava中的鼠标和键盘事件1、使用MouseListener借口处理鼠标事件鼠标事件有5种:按下鼠标键,释放鼠标键,点击鼠标键,鼠标进入和鼠标退出鼠标事件类型是MouseEvent,主要方法有:getX(),getY() 获取鼠标位置getModifiers() 获取鼠标左键或者右键getClickCount() 获取鼠标被点击的次数getSource() 获取鼠标发生的事件源事件源获得监视器的方法是addMouseListener(),移去监视器的方法是removeMouseListener() 处理事件源发生的时间的事件的接口是MouseListener 接口中有如下的方法mousePressed(MouseEvent) 负责处理鼠标按下事件mouseReleased(MouseEvent) 负责处理鼠标释放事件mouseEntered(MouseEvent) 负责处理鼠标进入容器事件mouseExited(MouseEvent) 负责处理鼠标离开事件mouseClicked(MouseEvent) 负责处理点击事件2、使用MouseMotionListener接口处理鼠标事件事件源发生的鼠标事件有2种:拖动鼠标和鼠标移动鼠标事件的类型是MouseEvent事件源获得监视器的方法是addMouseMotionListener()处理事件源发生的事件的接口是MouseMotionListener 接口中有如下的方法mouseDragged() 负责处理鼠标拖动事件mouseMoved() 负责处理鼠标移动事件3、控制鼠标的指针形状setCursor(Cursor.getPreddfinedCursor(Cursor.鼠标形状定义)) 鼠标形状定义见(书P 210)4、键盘事件键盘事件源使用addKeyListener 方法获得监视器键盘事件的接口是KeyListener 接口中有3个方法public void keyPressed(KeyEvent e) 按下键盘按键public void keyReleased(KeyEvent e) 释放键盘按键public void keyTypde(KeyEvent e) 按下又释放键盘按键Java多线程机制1、Java的线程类与Runnable接口Thread类public Thread() 创建线程对象public Thread(Runnable target) target 称为被创建线程的目标对象,负责实现Runnable接口线程优先级Thread类有三个有关线程优先级的静态常量:MIN_PRIORITY,MAX_PRIORITY,NORM_PRIORITY新建线程将继承创建它的副相承的优先级,用户可以调用Thread类的setPriority(int a)来修改a的取值:Thread.MIN_PRIORITY,Thread.MAX_PRIORITY,Thread.NORM_PRIORITY主要方法启动线程start()定义线程操作run()使线程休眠sleep()sleep(int millsecond) 以毫秒为单位的休眠时间sleep(int millsecond,int nanosecond) 以纳秒为单位的休眠时间currentThread() 判断谁在占用CPU的线程第二十章输入输出流1、FileInputStream类FileInputStream(String name) 使用给定的文件名name创建一个FileInputStream对象FileInputStream(File file) 使用File对象创建FileInpuStream对象File类有两个常用方法:File(String s) s确定文件名字File(String directory,String s) directory是文件目录例如:File f=new File("Myfile.dat");FileInputStream istream=new FileInputStream(f);处理I/O异常当出现I/O错误的时候,Java生成一个IOException(I/O异常)对象来表示这个错误的信号。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
JAVA中常用类的常用方法一、类1、clone()方法创建并返回此对象的一个副本。
要进行“克隆”的对象所属的类必须实现. Cloneable接口。
2、equals(Object obj)方法功能:比较引用类型数据的等价性。
等价标准:引用类型比较引用,基本类型比较值。
存在特例:对File、String、Date及封装类等类型来说,是比较类型及对象的内容而不考虑引用的是否为同一实例。
3、finalize()方法当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。
4、hashCode()方法返回该对象的哈希码值。
5、notify()方法唤醒在此对象监视器上等待的单个线程。
6、notifyAll()方法唤醒在此对象监视器上等待的所有线程。
7、toString()方法返回该对象的字符串表示。
在进行String与其它类型数据的连接操作时,自动调用toString()方法。
可以根据需要重写toString()方法。
8、wait()方法在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。
二、字符串相关类l String类charAt(int index) 返回指定索引处的 char 值。
compareTo(String anotherString) 按字典顺序比较两个字符串。
compareToIgnoreCase(String str) 按字典顺序比较两个字符串,不考虑大小写。
concat(String str) 将指定字符串连接到此字符串的结尾。
endsWith(String suffix) 测试此字符串是否以指定的后缀结束。
equals(Object anObject) 将此字符串与指定的对象比较。
equalsIgnoreCase(String anotherString) 将此 String 与另一个 String 比较,不考虑大小写。
indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。
indexOf(String str) 返回第一次出现的指定子字符串在此字符串中的索引。
lastIndexOf(int ch) 返回指定字符在此字符串中最后一次出现处的索引。
length() 返回此字符串的长度。
replace(char oldChar, char newChar)返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
split(String regex) 根据给定正则表达式的匹配拆分此字符串。
startsWith(String prefix) 测试此字符串是否以指定的前缀开始。
substring(int beginIndex)返回一个新的字符串,它是此字符串的一个子字符串。
该子字符串始于指定索引处的字符,一直到此字符串末尾。
substring(int beginIndex, int endIndex)返回一个新字符串,它是此字符串的一个子字符串。
该子字符串从指定的beginIndex 处开始,一直到索引 endIndex - 1 处的字符。
toCharArray() 将此字符串转换为一个新的字符数组。
toLowerCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
toUpperCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
trim() 返回字符串的副本,忽略前导空白和尾部空白。
valueOf(int i) 返回 int 参数的字符串表示形式。
StringBuffer类append () 为该StringBuffer对象添加字符序列,返回添加后的该StringBuffer 对象引用。
insert () 为该StringBuffer对象在指定位置插入字符序列,返回修改后的该StringBuffer对象引用。
delete (int start,int end) 可以删除从start开始到end-1为止的一段字符序列,返回修改后的该StringBuffer对象引用。
deleteCharAt(int index)移除此序列指定位置的 charreverse() 将字符序列逆序,返回修改后的该StringBuffer对象引用。
reverse() 将此字符序列用其反转形式取代。
setCharAt( (int index,char ch) 将给定索引处的字符设置为 ch。
StringBuilder类以后引入该类能够提供与StringBuffer 相同的功能,二者区别:a) StringBuffer类是线程安全的,而StringBuilder则不是,即不保证其对象的同步性,在多线程环境中是不安全的。
b) StringBuilder在性能上要比StirngBuffer 好一些。
StringTokenizer类类的功能是将当前字符串按照默认或指定的分隔符分解为多个片段。
主要功能方法:a) public boolean hasMoreTokens () 测试此 tokenizer 的字符串中是否还有更多的可用标记。
b) public String nextToken () 返回此 string tokenizer 的下一个标记。
三、基本数据类型封装类Integer类intValue() 以 int 类型返回该 Integer 的值parseInt(String s) 将字符串参数作为有符号的十进制整数进行分析。
reverse(int i) 返回通过反转指定 int 值的二进制补码表示形式中位的顺序而获得的值。
toHexString(int i) 以十六进制的无符号整数形式返回一个整数参数的字符串表示形式。
valueOf(int i) 返回一个表示指定的 int 值的 Integer 实例。
四、日期时间类型Date类类用于表示特定的时间点,精确到毫秒,但不支持日期的国际化和分时区显示。
主要功能方法:boolean after(Date when) 测试此日期是否在指定日期之后。
public int compareTo(Date anotherDate) 比较两个日期的顺序。
public boolean equals(Object obj) 比较两个日期的相等性。
public long getTime() 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
void setTime(long time)设置此 Date 对象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以后 time 毫秒的时间点。
public String toString()把此 Date 对象转换为以下形式的 String: dow mon dd hh:mm:ss zzz yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue, Wed, Thu, Fri, Sat)。
Calendar类主要方法:public static Calendar getInstance() 使用默认时区和语言环境获得一个日历。
public int get(int field) 返回给定日历字段的值。
public void set(int field, int value) 将给定的日历字段设置为给定值。
public final void set(int year, int month, int date) 设置日历字段 YEAR、MONTH 和 DAY_OF_MONTH 的值。
public final void set(int year, int month, int date, int hourOfDay, int minute, int second)设置字段 YEAR、MONTH、DAY_OF_MONTH、HOUR、MINUTE 和 SECOND 的值。
public abstract void add(int field, int amount) 根据日历的规则,为给定的日历字段添加或减去指定的时间量。
Locale类public static Locale getDefault() 获得此 Java 虚拟机实例的当前默认语言环境值。
public String getCountry() 返回此语言环境的国家/地区代码,将为空字符串或大写的 ISO 3166 两字母代码。
public String getLanguage() 返回此语言环境的语言代码,可以是空字符串或小写的 ISO 639 代码。
public final String getDisplayName() 返回适合向用户显示的语言环境名。
public static Locale[] getAvailableLocales() 返回所有已安装语言环境的数组。
TimeZone类类描述时区信息。
TimeZone被定义为抽象类,可以调用其静态方法getDefault()以获得该类的实例。
public static TimeZone getDefault() 获取此主机的默认 TimeZone。
public static TimeZone getTimeZone(String ID) 获取给定 ID 的 TimeZone。
GregorianCalendar类主要方法:public boolean isLeapYear(int year) 确定给定的年份是否为闰年。
DateFormat类类提供了将日期/时间信息进行格式化处理的功能主要方法:public static final DateFormat getDateInstance()获得日期 formatter,该 formatter 具有默认语言环境的默认格式化风格。
public static final DateFormat getDateTimeInstance()获得日期/时间 formatter,该 formatter 具有默认语言环境的默认格式化风格。
public static final DateFormat getDateTimeInstance() 获得日期/时间 formatter,该 formatter 具有默认语言环境的默认格式化风格。
public final String format(Date date) 将一个 Date 格式化为日期/时间字符串。
SimpleDateFormat类void applyPattern(String pattern) 将给定模式字符串应用于此日期格式。
五、数字相关类型Random类类是基于“线性同余”算法的一种伪随机数序列生成器。