Does Java have something like C#'s ref and out keywords?

后端 未结 7 1529
陌清茗
陌清茗 2020-11-27 03:31

Something like the following:

ref example:

void changeString(ref String str) {
    str = \"def\";
}

void main() {
    String abc = \"abc\";
    chan         


        
7条回答
  •  囚心锁ツ
    2020-11-27 03:49

    java has no standard way of doing it. Most swaps will be made on the list that is packaged in the class. but there is an unofficial way to do it:

    package Example;
    
    import java.lang.reflect.Field;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    
    
     public class Test{
    
    
    private static  void SetValue(T obj,T value){
        try {
            Field f = obj.getClass().getDeclaredField("value");
            f.setAccessible(true);
            f.set(obj,value);
            } catch (IllegalAccessException | IllegalArgumentException | 
                NoSuchFieldException | SecurityException ex) {
                Logger.getLogger(CautrucjavaCanBan.class.getName()).log(Level.SEVERE, 
           null, ex);
            }
    }
    private  static  void permutation(Integer a,Integer b){
        Integer tmp = new Integer(a);
        SetValue(a, b);
        SetValue(b, tmp);
    }
     private  static  void permutation(String a,String b){
        char[] tmp = a.toCharArray();
        SetValue(a, b.toCharArray());
        SetValue(b, tmp);
    }
    public static void main(String[] args) {
        {
            Integer d = 9;
            Integer e = 8;
            HoanVi(d, e);
            System.out.println(d+" "+ e);
        }
        {
            String d = "tai nguyen";
            String e = "Thai nguyen";
            permutation(d, e);
            System.out.println(d+" "+ e);
        }
    }
    
    }
    

提交回复
热议问题