zoukankan      html  css  js  c++  java
  • 【Java学习笔记】java.lang包学习

    作者:gnuhpc
    出处:http://www.cnblogs.com/gnuhpc/

    1.特性——不用import
    2.String
    String x = "abc"; <=> String x= new String("abc");
    因为public final class java.lang.String;
    而String x="The number " + y;中,在JAVA中不管是什么变量或者对象,在对String进行加和时都转化为String。
    3.Annotation
    注解(Annotation) 为我们在代码中添加信息提供了一种形式化的方法,是我们可以在稍后某个时刻方便地使用这些数据(通过解析注解来使用这些数据)。注解的语法比较简单,除了@符号的使用以外,它基本上与java的固有语法一致,java内置了三种注解,定义在java.lang包中。
          @Override  表示当前方法是覆盖父类的方法。
          @Deprecated  表示当前元素是不赞成使用的。
          @SuppressWarnings 表示关闭一些不当的编译器警告信息。
    # import java.lang.annotation.Documented; 
    # import java.lang.annotation.Inherited; 
    # import java.lang.annotation.Retention; 
    # import java.lang.annotation.Target; 
    # import java.lang.annotation.ElementType; 
    # import java.lang.annotation.RetentionPolicy; 
    # /*
    #  * 元注解@Target,@Retention,@Documented,@Inherited
    #  * 
    #  *     @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括:
    #  *         ElemenetType.CONSTRUCTOR 构造器声明
    #  *         ElemenetType.FIELD 域声明(包括 enum 实例)
    #  *         ElemenetType.LOCAL_VARIABLE 局部变量声明
    #  *         ElemenetType.METHOD 方法声明
    #  *         ElemenetType.PACKAGE 包声明
    #  *         ElemenetType.PARAMETER 参数声明
    #  *         ElemenetType.TYPE 类,接口(包括注解类型)或enum声明
    #  *         
    #  *     @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括:
    #  *         RetentionPolicy.SOURCE 注解将被编译器丢弃
    #  *         RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃
    #  *         RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
    #  *         
    #  *     @Documented 将此注解包含在 javadoc 中
    #  *     
    #  *     @Inherited 允许子类继承父类中的注解
    #  *   
    #  */ 
    下面是一个使用注解 和 解析注解的实例
    package Test_annotation;
    import java.lang.reflect.Method;
    public class Test_1 {
    /*
      * 被注解的三个方法
      */
    @Test(id = 1, description = "hello method_1")
    public void method_1() {
    }
    @Test(id = 2)
    public void method_2() {
    }
    @Test(id = 3, description = "last method")
    public void method_3() {
    }
    /*
      * 解析注解,将Test_1类 所有被注解方法的信息打印出来
      */
    public static void main(String[] args) {
      Method[] methods = Test_1.class.getDeclaredMethods();
      for (Method method : methods) {
       /*
        * 判断方法中是否有指定注解类型的注解
        */
       boolean hasAnnotation = method.isAnnotationPresent(Test.class);
       if (hasAnnotation) {
        /*
         * 根据注解类型返回方法的指定类型注解
         */
        Test annotation = method.getAnnotation(Test.class);
        System.out.println("Test( method = " + method.getName()
          + " , id = " + annotation.id() + " , description = "
          + annotation.description() + " )");
       }
      }
    }
    }
    输出结果如下:
        Test( method = method_1 , id = 1 , description = hello method_1 )
        Test( method = method_2 , id = 2 , description = no description )
        Test( method = method_3 , id = 3 , description = last method )
    4.instrument
    使用 Instrumentation,开发者可以构建一个独立于应用程序的代理程序(Agent),用来监测和协助运行在 JVM 上的程序,甚至能够替换和修改某些类的定义。有了这样的功能,开发者就可以实现更为灵活的运行时虚拟机监控和 Java 类操作了,这样的特性实际上提供了一种虚拟机级别支持的 AOP 实现方式,使得开发者无需对 JDK 做任何升级和改动,就可以实现某些 AOP 的功能了。在 Java SE 5 中,Instrument 要求在运行前利用命令行参数或者系统参数来设置代理类,在实际的运行之中,虚拟机在初始化之时(在绝大多数的 Java 类库被载入之前),instrumentation 的设置已经启动,并在虚拟机中设置了回调函数,检测特定类的加载情况,并完成实际工作。但是在实际的很多的情况下,我们没有办法在虚拟机启动之时就为其设定代理,这样实际上限制了 instrument 的应用。而 Java SE 6 的新特性改变了这种情况,通过 Java Tool API 中的 attach 方式,我们可以很方便地在运行过程中动态地设置加载代理类,以达到 instrumentation 的目的。
    举例说明:我们想把如下程序中的6改为7
    public class HelloWorld {
        public static void main(String arg[]) {
            System.out.println("The number six is 6");
        }
    }
    那么我们要设定一个Agent,这个类就会attach在主程序上了~
    import java.lang.instrument.Instrumentation;
    public class MySimpleAgent {
        public static void premain(String agentArgs,Instrumentation inst) {
            inst.addTransformer(new MySimpleTransformer());
        }
    }
    在这个Agent中有一个MySimpleTransformer类派生出对象作为转换器。我们看看如何定义MySimpleTransformer类。
    import java.lang.instrument.ClassFileTransformer;
    import java.lang.instrument.IllegalClassFormatException;
    import java.security.ProtectionDomain;
    public class MySimpleTransformer implements ClassFileTransformer {
        public byte[] transform(ClassLoader classloader,
                                String classname,
                                Class redefinedclass,
                                ProtectionDomain protectiondomain,
                                byte b[]) throws IllegalClassFormatException {
            if(!classname.endsWith("HelloWorld"))
                return(null);
            String line = "";
            for(int i=0; i<b.length; i++) {
                line += Byte.toString(b[i]) + " ";
                if(line.length() > 60) {
                    System.out.println(line);
                    line = "";
                }
                if(b[i] == (byte)'6')
                    b[i] = (byte)'7';
            }
            System.out.println(line);
            System.out.println("The number of bytes in HelloWorld: " + b.length);
            return(b);
        }
    }
    使用下列命令创建一个JAR包:
    javac *.java 2>&1 | more
    jar -cfm MyAgent.jar agentmantext MySimpleAgent.class MySimpleTransformer.class
    其中的agentmantext的内容如下:
    Premain-Class: MySimpleAgent
    而运行方法则如下:
    java -javaagent:MyAgent.jar HelloWorld
    5.java.lang.ref
    Java 2 平台引入了 java.lang.ref 包,其中包括的类可以让您引用对象,而不将它们留在内存中。这些类还提供了与垃圾收集器(garbage collector)之间有限的交互。
    先“由强到弱”(只的是和垃圾回收器的关系)明确几个基本概念:
    strong references是那种你通常建立的reference,这个reference就是强可及的。这个不会被自动回收。例如:StringBuffer buffer = new StringBuffer();其中这个buffer就是强引用,之所以称为“强”是取决于它如何处理与Garbage Collector的关系的:它是无论如何都不会被回收的。够强的。强引用在某些时候是有个问题的,下边的一个哈希表实例就是很好的说明。而且还有一个问题就是在缓冲上,尤其是诸如图片等大的结构上。我们在内存中开辟一块区域放置图片缓冲,那我们就希望有个指针指向那块区域。此时若是使用强引用则回强迫图片留在内存,当你觉得不需要的时候你需要手动移除,否则就是内存泄漏。
    WeakReference则类似于可有可无的东西。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存,说白了就是一个没那么strong要求垃圾回收器将一个对象保留在内存中。不过,由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些只具有弱引用的对象。常说的Unreachable和弱引用指代的是一个意思。这可能还是说不清楚,那么我举个例子:
    你有一个类叫做Widget,但是由于某种原因它不能通过继承来添加一项功能。当我们想从这个对象中取出一些信息的时候怎么办呢?假设我们需要监视每个Widget的serial Number,但是这个Widget却偏偏没有这个属性,而且还不可继承...这时候我们想到了用HashMaps:serialNumberMap.put(widget, widgetSerialNumber);
    这不就截了嘛~表面上看起来是ok的,但是正是Widget这个Strong Reference产生了问题。当我们设定某个Widget的SerialNumber不需要的时候,那么要从这个映射表中除去这个映射对,否则我们就有了内存泄漏或者是出错(移除了有效的SerialNumber)。这个问题听起来很耳熟,是的,在没有垃圾管理机制的语言中这是个常见问题,在JAVA中我们不用担心。因为我们有WeakReference。我们使用内置的WeakHashMap类,这个类和哈希表HashMap几乎一样,但就是在键key的地方使用了WeakReference,若一个WeakHashMap key成为了垃圾,那么它对应的入口就会自动被移除。这就解决了上述问题~
    SoftReference则也类似于可有可无的东西。如果内存空间足够,垃圾回收器就不会回收它,如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。弱引用与软引用的区别在于:具有WeakReference的对象拥有更短暂的生命周期。或者说SoftReference比WeakReference对回收它所指的对象不敏感。一个WeakReference对象会在下一轮的垃圾回收中被清理,而SoftReference对象则会保存一段时间。SoftReferences并不会主动要求与WeakReference有什么不同,但是实际上SoftReference对象一般在内存充裕时一般不会被移除,这就是说对于创建缓冲区它们是不错的选择。它兼有了StrongReference和WeakReference的好处,既能停留在内存中,又能在内存不足是去处理,这一切都是自动的!
    PhantomReference为"虚引用",顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收,也就是说其get方法任何时间都会返回null。虚引用主要用来跟踪对象被垃圾回收的活动。其必须和引用队列(ReferenceQueue)联合使用,这是与弱引用和软引用最大的不同。WeakReference是在垃圾回收活动之前将对象入队的,理论上讲这个对象还可以使用finalize()方法使之重生,但是WeakReference仍然是死掉了。PhantomReferences对象是在对象从内存中清除出去的时候才入队的。也就是说当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之关联的引用队列中。程序可以通过判断引用队列中是否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。程序如果发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。它限制了finalize()方法的使用,更安全也更高效。
    我们看看这个包给我们提供了什么类?
    WeakReference 类
    WeakReference weakref = new WeakReference(ref);
    这样 weakref 就是 ref 指向对象的一个 weak reference。要引用这个 weak reference 指向的对象可以用 get 方法。把对象的 weak reference 放入 Hashtable 或者缓存中,当没有 strong reference 指向他们的时候,对象就可以被垃圾收集器回收了。实际上,有一个 WeakHashMap 就是专门做这个事的。一旦WeakReference使用get方法返回null的时候,它指向的对象已经变成了垃圾,这个weakref对象也没什么用处了。这就需要有一些清理工作了。而ReferenceQueue类就是做这个的,要是你向ReferenceQueue类传递了一个WeakReference的构造方法,那么当引用所指的对象成为垃圾时,这个引用的对象就会被自动插入到这个引用队列中。你可以在一定时间间隔内处理这个队列。
    SoftReference 类
    可用来实现智能缓存(java.lang.ref.SoftReference is a relatively new class, used to implement smart caches.)假定你有一个对象引用,指向一个大数组:
    Object obj = new char[1000000];
    并且如果可能的话,你打算一直保存这个数组,但是如果内存极其短缺的话,你乐于释放这个数组。你可以使用一个
    soft reference:
    SoftReference ref = new SoftReference(obj);
    Obj是这个soft reference的引用。在以后你用以下的方式检测这个引用:
    if (ref.get() == null)// (referent has been cleared)
    else// (referent has not been cleared)
    如果这个引用已经被清除了,那么垃圾回收器会收回它所使用的空间,并且你缓存的对象也已经消失。需要注意的是,如果这个指示物还有对它的别的引用,那么垃圾回收器将不会清除它。这个方案可以被用来实现各种不同类型的缓存,这些缓存的特点是只要有可能对象就会被一直保存下来,但是如果内存紧张对象就被清除掉。
    注意:软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收,Java虚拟机就会把这个软引用加入到与之关联的引用队列中。
    PhantomReference 类

    举个例子:
    import java.lang.ref.*;
    public class References {
      public static void main(String[] args) {
        Object weakObj, phantomObj;
        Reference ref;
        WeakReference weakRef;
        PhantomReference phantomRef;
        ReferenceQueue weakQueue, phantomQueue;
        weakObj    = new String("Weak Reference");
        phantomObj = new String("Phantom Reference");
        weakQueue    = new ReferenceQueue();
        phantomQueue = new ReferenceQueue();
        weakRef    = new WeakReference(weakObj, weakQueue);
        phantomRef = new PhantomReference(phantomObj, phantomQueue);
        // Print referents to prove they exist.  Phantom referents
        // are inaccessible so we should see a null value.
        System.out.println("Weak Reference: " + weakRef.get());
        System.out.println("Phantom Reference: " + phantomRef.get());
        // Clear all strong references
        weakObj    = null;
        phantomObj = null;
        // Invoke garbage collector in hopes that references
        // will be queued
        System.gc();
        // See if the garbage collector has queued the references
        System.out.println("Weak Queued: " + weakRef.isEnqueued());
        // Try to finalize the phantom references if not already
        if(!phantomRef.isEnqueued()) {
          System.out.println("Requestion finalization.");
          System.runFinalization();
        }
        System.out.println("Phantom Queued: " + phantomRef.isEnqueued());
        // Wait until the weak reference is on the queue and remove it
        try {
          ref = weakQueue.remove();
          // The referent should be null
          System.out.println("Weak Reference: " + ref.get());
          // Wait until the phantom reference is on the queue and remove it
          ref = phantomQueue.remove();
          System.out.println("Phantom Reference: " + ref.get());
          // We have to clear the phantom referent even though
          // get() returns null
          ref.clear();
        } catch(InterruptedException e) {
          e.printStackTrace();
          return;
        }
      }
    }
    5.java.lang.reflect
    可以让你从public的方法和变脸中获取信息,称为reflect是因为Java称之为reflective,本来用来设计优化器和调试器的,可以使用getclass()方法得到相关类。getFields()方法使我们能得到其中的一些变量信息。而getMethods()方法则得到类的相关方法信息。getInterfaces()方法可以得到相关接口信息。
    例如:
    import java.lang.reflect.Field;
    public class FieldList {
        public int x;
        public double y;
        public static void main(String arg[]) {
            FieldList flist = new FieldList();
            Class thisClass = flist.getClass();
            Field field[] = thisClass.getFields();
            for(int i=0; i<field.length; i++)
                System.out.println(field[i]);
        }
    }
    -------------------------------------
    import java.lang.reflect.Method;
    public class MethodList {
        public static void main(String arg[]) {
            MethodList mlist = new MethodList();
            Class mlistClass = mlist.getClass();
            Method method[] = mlistClass.getMethods();
            for(int i=0; i<method.length; i++)
                System.out.println(method[i]);
        }
        public double sum(int x,float y) {
            return((double)(x + y));
        }
    }
    ----------------------------------------
    import javax.swing.event.ChangeListener;
    import javax.swing.event.ChangeEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.ItemEvent;
    public class InterfaceList implements ChangeListener, ItemListener {
        public static void main(String arg[]) {
            InterfaceList ilist = new InterfaceList();
            Class thisClass = ilist.getClass();
            Class iface[] = thisClass.getInterfaces();
            for(int i=0; i<iface.length; i++)
                System.out.println(iface[i]);
        }
        public void stateChanged(ChangeEvent e) {
        }
        public void itemStateChanged(ItemEvent e) {
        }
    }
    ----------------------------------
    import java.lang.reflect.Modifier;
    import java.lang.reflect.Constructor;
    public class ModifierList {
        public ModifierList() {
        }
        public static void main(String arg[]) {
            ModifierList mlist = new ModifierList();
            Class mlistClass = mlist.getClass();
            Constructor constructor[] = mlistClass.getConstructors();
            int mod = constructor[0].getModifiers();
            System.out.println("The constructor is:");
            if(Modifier.isAbstract(mod))
                System.out.println("abstract");
            else
                System.out.println("not abstract");
            if(Modifier.isFinal(mod))
                System.out.println("final");
            else
                System.out.println("not final");
            if(Modifier.isInterface(mod))
                System.out.println("interface");
            else
                System.out.println("not interface");
            if(Modifier.isNative(mod))
                System.out.println("native");
            else
                System.out.println("not native");
            if(Modifier.isPrivate(mod))
                System.out.println("private");
            else
                System.out.println("not private");
            if(Modifier.isProtected(mod))
                System.out.println("protected");
            else
                System.out.println("not protected");
            if(Modifier.isPublic(mod))
                System.out.println("public");
            else
                System.out.println("not public");
            if(Modifier.isStatic(mod))
                System.out.println("static");
            else
                System.out.println("not static");
            if(Modifier.isStrict(mod))
                System.out.println("strict");
            else
                System.out.println("not strict");
            if(Modifier.isSynchronized(mod))
                System.out.println("synchronized");
            else
                System.out.println("not synchronized");
            if(Modifier.isTransient(mod))
                System.out.println("transient");
            else
                System.out.println("not transient");
            if(Modifier.isVolatile(mod))
                System.out.println("volatile");
            else
                System.out.println("not volatile");
        }
    }
    --------------------------------------------------
    6.java.lang.management
    你可以看看JVM是怎么处理内存的。JVM处理内存分为两部分:
    Heap堆,加载类和对象的,这个就是垃圾回收器作用的地方。
    Non-Heap,有些Garbage Collector也作用于此。
    看下边这个例子:
    import java.lang.management.ManagementFactory;
    import java.lang.management.MemoryMXBean;
    import java.lang.management.MemoryUsage;
    public class ShowMemory {
        static String x;
        public static void main(String arg[]) {
            ShowMemory sm = new ShowMemory();
            sm.show();
            x = "";
            for(int i=0; i<1000; i++)
                x += " string number " + i;
            sm.show();
            x = null;
            sm.show();
            MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
            mem.gc();
            sm.show();
        }
        void show() {
            MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
            MemoryUsage heap = mem.getHeapMemoryUsage();
            System.out.println("Heap committed=" + heap.getCommitted() +
                                " init=" + heap.getInit() +
                                " max=" + heap.getMax() +
                                " used=" + heap.getUsed());
        }
    }
    还可以支持你看看系统信息:
    import java.lang.management.ManagementFactory;
    import java.lang.management.OperatingSystemMXBean;
    public class ShowSystem {
        public static void main(String arg[]) {
            OperatingSystemMXBean op = ManagementFactory.getOperatingSystemMXBean();
            System.out.println("Architecture: " + op.getArch());
            System.out.println("Processors: " + op.getAvailableProcessors());
            System.out.println("System name: " + op.getName());
            System.out.println("System version: " + op.getVersion());
            System.out.println("Last minute load: " + op.getSystemLoadAverage());
        }
    }
    还可以知道编译信息、类加载信息、JVM的信息、线程信息。

    作者:gnuhpc
    出处:http://www.cnblogs.com/gnuhpc/

  • 相关阅读:
    jQuery实现动态搜索显示功能
    面试
    Struts1和Struts2的区别和对比(完整版)
    JAVA调用增删改的存储过程
    Spring MVC入门
    jQuery Ajax通用js封装
    js ==与===区别
    shell脚本awk
    C++对象模型初窥
    再见,2021
  • 原文地址:https://www.cnblogs.com/gnuhpc/p/2822256.html
Copyright © 2011-2022 走看看