Results 1 to 6 of 6
  1. #1
    nuffsaidM8 is offline Member
    Join Date
    Jul 2015
    Posts
    5
    Rep Power
    0

    Default Created objects have null fields

    In short, I create this class to use as a constructor.
    Java Code:
            public List<Object> storedDeaths; //objects will eventually be sent here
    	
    	public class Unlosable {
    		public Player pl;
    		public List<ItemStack> storedHits;
    		public String storedPlayerName;
    		
    		public Unlosable(Player nameOfPlayer, List<ItemStack> items1){
    			Player pl = nameOfPlayer;
    			@SuppressWarnings("unused")
    			String storedPlayerName = pl.getName();
    			@SuppressWarnings("unused")
    			List<ItemStack> storedHits = items1;
    		};
    	};
    And when I create an object here and then log the fields of that object to a player:

    Java Code:
            Unlosable myUnlosable = new Unlosable(p, hits); //create an object
            p.sendMessage(myUnlosable.storedPlayerName + "    :    " + myUnlosable.storedHits);  //log the fields to the player
    
    
    
            storedDeaths.add(new Unlosable(p, hits)); //create a REAL object and send it to the list
    Both the fields of the object are null. What am I doing wrong? People are saying that I create the variables but never use them for anything, but I DO try to access the fields of an object later in my code.

    Just in case, here is my whole class (doubt you will need it):

    Java Code:
            package com.nuffsaidM8.undroppable;
    
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.bukkit.Bukkit;
    import org.bukkit.Material;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.entity.Item;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.PlayerDeathEvent;
    import org.bukkit.event.player.PlayerDropItemEvent;
    import org.bukkit.event.player.PlayerRespawnEvent;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.meta.ItemMeta;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public class Undroppable extends JavaPlugin implements Listener {
    	
    	public List<Object> storedDeaths;
    	
    	public class Unlosable {
    		public Player pl;
    		public List<ItemStack> storedHits;
    		public String storedPlayerName;
    		
    		public Unlosable(Player nameOfPlayer, List<ItemStack> items1){
    			Player pl = nameOfPlayer;
    			@SuppressWarnings("unused")
    			String storedPlayerName = pl.getName();
    			@SuppressWarnings("unused")
    			List<ItemStack> storedHits = items1;
    		};
    	};
    	
    	
    	
    	
    	
    	
    	
    	FileConfiguration config = getConfig();
    
    	public void onEnable() {
    		this.getServer().getPluginManager()
    		.registerEvents(this, this);
    config.options().copyDefaults(true);
    saveDefaultConfig();
    	};
    
    	public void onDisable() {
    
    	};
    	
    
    	private static String OBC_PREFIX = Bukkit.getServer().getClass().getPackage().getName();
    	private static String NMS_PREFIX = OBC_PREFIX.replace("org.bukkit.craftbukkit", "net.minecraft.server");
    	
    	private static Class<?> nmsCraftItemStackClass;
    	private static Class<?> nmsItemStackClass;
    	private static Method nmsCopyMethod;
    	private static Method nmsGetNameMethod;
    	
    	public static String getTheName(ItemStack itemStack) {
    		if(itemStack == null || itemStack.getType() == Material.AIR) return "Air";
    		try {
    			if(nmsCraftItemStackClass == null)
    				nmsCraftItemStackClass = Class.forName(OBC_PREFIX + ".inventory.CraftItemStack");
    			if(nmsCopyMethod == null)
    				nmsCopyMethod = nmsCraftItemStackClass.getMethod("asNMSCopy", ItemStack.class);
    			if(nmsItemStackClass == null)
    				nmsItemStackClass = Class.forName(NMS_PREFIX + ".ItemStack");
    			Object nmsItemStack = nmsCopyMethod.invoke(null, itemStack);
    			if(nmsGetNameMethod == null)
    				nmsGetNameMethod = nmsItemStackClass.getMethod("getName");
    			Object itemName = nmsGetNameMethod.invoke(nmsItemStack);
    			if(itemName != null)
    				return (String) itemName;
    		} catch(Exception ex) {
    			ex.printStackTrace();
    		};
    		String displayName = itemStack.getType().name();
    		if(!displayName.contains("_"))
    			return capitalizeFormat(displayName);
    		else {
    			String[] splitName = displayName.split("_");
    			displayName = new String();
    			for(String str : splitName) {
    				str = capitalizeFormat(str);
    				displayName += displayName.isEmpty() ? str : " " + str;
    			};
    		};
    		return displayName;
    	};
    	
    	private static String capitalizeFormat(String str) {
    		String firstLetter = str.substring(0, 1).toUpperCase();
    		return firstLetter + str.substring(1).toLowerCase();
    	};
    	
    	List<String> undroppableItems = config.getStringList("undroppable");
    	List<String> keepOnDeath = config.getStringList("keepondeath");
    	
    	
    	
    
    	public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
    		
    		if(!(sender instanceof Player)){
    	    	sender.sendMessage("You must be a player to use this command.");
    	    	return false;
    	    };
    		
    		Player player = (Player) sender;
    		
    		if(commandLabel.equalsIgnoreCase("whatsundroppable")){
    			player.sendMessage("------------------------");
    			for (int i = 0; i < undroppableItems.size(); i++){   	        
    				
    				player.sendMessage(undroppableItems.get(i));
    				
    			};
    			player.sendMessage("------------------------");
    			return true;
    		};
    		
    		if(commandLabel.equalsIgnoreCase("whatskeptondeath")){
    			player.sendMessage("------------------------");
    			for (int j = 0; j < keepOnDeath.size(); j++){  
    				
    				player.sendMessage(keepOnDeath.get(j));
    				
    			};
    			player.sendMessage("------------------------");
    			return true;
    		};
    		
    		
    		return false;
    	};
    	
    	@EventHandler
    	public void onDrop(PlayerDropItemEvent event){
    		Player dropper = event.getPlayer();
    		Item item = event.getItemDrop();
    		ItemStack stack = item.getItemStack();
    		ItemMeta droppedItemMeta = stack.getItemMeta();
    		String checkThis;
    		if(droppedItemMeta.getDisplayName() != null){
    			checkThis = droppedItemMeta.getDisplayName();
    		} else {
    			checkThis = getTheName(stack);
    		};
    		
    		int count = 0;
    		String myItem;
    		
    		for (int l = 0; l < undroppableItems.size(); l++){ 	
    			myItem = undroppableItems.get(l);
    			if(!(myItem.equalsIgnoreCase(checkThis))) {
    				count += 1;
    			};
    		};
    		
    		
    		if(count == undroppableItems.size()){
    		} else {
    			dropper.sendMessage("You cannot drop this item!");
    			event.setCancelled(true);
    		};
    	};
    	
    	List<ItemStack> hits = new ArrayList<ItemStack>();
    	
    	@EventHandler
    	public void onDeath(PlayerDeathEvent event) {
    		hits.clear();
    		Player p  = event.getEntity();
    		p.sendMessage("You died");
    		List<ItemStack> drops = event.getDrops();
    		String currentItem;
    		for (int o = 0; o < drops.size(); o++) {
    			ItemStack currentCheck = drops.get(o);
                ItemMeta current = currentCheck.getItemMeta();
    			if(current.getDisplayName() != null){
    				currentItem = current.getDisplayName();
    			} else {
    				currentItem = getTheName(currentCheck);
    			};
    			p.sendMessage("You dropped: " + currentItem + ".");
    			for(int m = 0; m < keepOnDeath.size(); m++){
    				if(currentItem.equalsIgnoreCase(keepOnDeath.get(m))){
    					p.sendMessage("Item will be returned: " + currentItem + ".");
    					hits.add(drops.get(o));
    				};
    			};
            };
            
            
            p.sendMessage(p.toString() + "    :    " + hits); //test to see if hits and p are populated (which they are)
    
            //error is here
            Unlosable myUnlosable = new Unlosable(p, hits);
            p.sendMessage(myUnlosable.storedPlayerName + "    :    " + myUnlosable.storedHits);
    
            storedDeaths.add(new Unlosable(p, hits)); //the real code breaking error here
    	};
    	
    	@EventHandler
    	public void onRespawn(PlayerRespawnEvent event){
    		Player respawned = event.getPlayer();
    		String respawnedName = respawned.getName();
    		Unlosable myUnlosable;
    		List<ItemStack> returnedItemStacks;
    		for(int c = 0; c < storedDeaths.size(); c++){
    			myUnlosable = (Unlosable) storedDeaths.get(c);
    			if(myUnlosable.storedPlayerName == respawnedName){
    				returnedItemStacks = myUnlosable.storedHits;
    				for(int a = 0; a < returnedItemStacks.size(); a++){
    					respawned.getInventory().addItem(returnedItemStacks.get(a));
    				};
    				storedDeaths.remove(c);
    			};
    		};
    	};
    };

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Created objects have null fields

    Java Code:
    	public class Unlosable {
    		public Player pl;
    		public List<ItemStack> storedHits;
    		public String storedPlayerName;
    		
    		public Unlosable(Player nameOfPlayer, List<ItemStack> items1){
    			Player pl = nameOfPlayer;
    			@SuppressWarnings("unused")
    			String storedPlayerName = pl.getName();
    			@SuppressWarnings("unused")
    			List<ItemStack> storedHits = items1;
    		};
    	};
    The fact you felt a need to use @SuppressWarning where you did should be a hint.
    Those warnings were telling you what the problem was.

    You declared local (to the constructor) versions of your attributes, which hid the actual class attributes...and those were the ones being set by the constructor parameters, not the actual attributes.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Created objects have null fields

    Hi I'm Gimby, and I suck at paint.

    (there is supposed to be a picture attachment here, should you not see it yet)
    Attached Thumbnails Attached Thumbnails Created objects have null fields-wrong_place.png  
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  4. #4
    nuffsaidM8 is offline Member
    Join Date
    Jul 2015
    Posts
    5
    Rep Power
    0

    Default Re: Created objects have null fields

    Quote Originally Posted by gimbal2 View Post
    Hi I'm Gimby, and I suck at paint.

    (there is supposed to be a picture attachment here, should you not see it yet)
    What I want is to be able to create an object using this constructor that stores its own data as the field, data different for each object. how do I modify the constructor to do this?

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Created objects have null fields

    Don't redeclare your fields in your constructor. Just assign to them.

    e.g.

    Java Code:
    private int myField;
    MyConstructor(int field) {
    myField = field;  <--------this
    int myField = field; <---------not this.
    }
    Read Tolls' last paragraph in previous post.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    5,114
    Rep Power
    12

    Default Re: Created objects have null fields

    A good book on basic Java programming is probably the better solution here.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Sorting a Vector by Fields of Objects Stored in it
    By Willriker in forum New To Java
    Replies: 10
    Last Post: 06-15-2013, 04:18 PM
  2. Lifecycle of objects created inside a function?
    By petzeee in forum New To Java
    Replies: 2
    Last Post: 01-25-2013, 09:22 AM
  3. How to find the objects are created in heap only?
    By akiravelmont in forum New To Java
    Replies: 1
    Last Post: 12-07-2012, 06:47 PM
  4. Replies: 8
    Last Post: 08-13-2011, 06:02 PM
  5. I am created this program.but it shows null pointer exception...can any one help me..
    By vetrivelmanian in forum Threads and Synchronization
    Replies: 3
    Last Post: 07-26-2011, 11:30 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •